Home > Blockchain >  Error A value of type 'Color?' can't be assigned to a variable of type 'Color�
Error A value of type 'Color?' can't be assigned to a variable of type 'Color�

Time:05-23

I have a widget called CircleIcon, where I'm trying to add bgcolor by named argument.

class CircleIcon extends StatelessWidget {
    final IconData icon;
    final double iconSize;
    final Color bgColor;
    final VoidCallback onPressed;

    const CircleIcon({
        Key? key,
        required this.icon,
        this.iconSize = 25.0,
        this.bgColor = Colors.grey[200],
        required this.onPressed,
    }) : super(key: key);

As a default bg color , I'm trying to keep Colors.grey[200], but I'm getting error A value of type 'Color?' can't be assigned to a variable of type 'Color'. If I change it to Colors.grey then it's working. What the type I will use for Colors.grey[200] ?

CodePudding user response:

Try below code, hope its help to you.

The Colors.grey[200] is not constatnt if you use simple Colors.grey is accept so I used const value like const Color(0xFFEEEEEE)

class CircleIcon extends StatelessWidget {  
  final IconData icon;
  final double iconSize;
  final Color  bgColor;
  final VoidCallback onPressed;

  const CircleIcon({
    Key? key,
    required this.icon,
    this.iconSize = 25.0,
    this.bgColor = const Color(0xFFEEEEEE),
    required this.onPressed,
  }) : super(key: key);
}

Refer my answer here also.

Refer Flutter Colors here

CodePudding user response:

The problem is with null values. You need to define bgColor with nullable type

final Color? bgColor;

CodePudding user response:

You can use (!) operator:

this.bgColor = Colors.grey[200]!

OR

use shade on the Color:

this.bgColor = Colors.grey.shade200
  • Related