Home > Mobile >  cant refactor color with shade in Flutter
cant refactor color with shade in Flutter

Time:10-04

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

CodePudding user response:

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),

CodePudding user response:

Try this.

this.buttonColor = Colors.grey, 

or,

this.buttonColor =Color(0xFFE0E0E0) //This is equal to grey[w300]

for more details https://dart.dev/tools/diagnostic-messages#non_constant_default_value

  • Related