cant refactor color with shade in Flutter

Issue

I am trying to refactor my code. This is my Code ,I am getting Problem

import 'package:flutter/material.dart';

class AppBarButton extends StatelessWidget {
  const AppBarButton(
      {Key? key,
      required this.buttnoAction,
      this.buttonColor = Colors.grey[300], // the error getting is " The default value of an optional parameter must be constant. " 
      required this.iconLogo,
      this.iconSize = 15,})
      : super(key: key);

  final void Function() buttnoAction;
  final Color buttonColor;
  final IconData iconLogo;
  final double iconSize;

  @override
  Widget build(BuildContext context) {
    return Container(
      child: IconButton(
        onPressed: buttnoAction,
        icon: Icon(
          iconLogo,
          color: buttonColor,
          size: iconSize,
        ),
      ),
    );
  }
}

Here I don’t get an error while using Colors.grey but can’t use Colors.grey[300] how to fix this.
why I am getting this error

Solution

Not entirely sure but it is probably because Colors.grey is a const (a constant) and Colors.grey[300] is not a const and therefore not accepted as default value of an optional parameter.

If you still want to use Colors.grey[300] as default value, you need to make it a const, this can be done by using the corresponding color code:

const Color(0xFFE0E0E0)

so change this

this.buttonColor = Colors.grey[300],

into this

this.buttonColor = const Color(0xFFE0E0E0),

Answered By – BJW

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *