Abu Sayed
Abu Sayed

Reputation: 125

Error A value of type 'Color?' can't be assigned to a variable of type 'Color' in flutter

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] ?

Upvotes: 0

Views: 1131

Answers (5)

mitchiri_neko
mitchiri_neko

Reputation: 2267

You are reading Map, which Color can't process it.

Instead, use Colors.grey.shade200 or Color(0xFFEEEEEE)

Upvotes: 0

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63569

You are using const before CircleIcon and using Colors.blue[100] means reading map and which is not constant. It will get data on runtime.

You can explore it on GitHub

static const MaterialColor grey = MaterialColor(
    _greyPrimaryValue,
    <int, Color>{
       50: Color(0xFFFAFAFA),
      100: Color(0xFFF5F5F5),
      200: Color(0xFFEEEEEE),
      //....
    },
  );

Therefore, you can not use const with color[value].

while grey[200] is Color(0xFFEEEEEE), you can use it.

this.bgColor = const Color(0xFFEEEEEE),

Upvotes: 0

greetal
greetal

Reputation: 1537

You can use (!) operator:

this.bgColor = Colors.grey[200]!

OR

use shade on the Color:

this.bgColor = Colors.grey.shade200

Upvotes: 1

Ravindra S. Patil
Ravindra S. Patil

Reputation: 14775

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

Upvotes: 1

Harsh Kanjariya
Harsh Kanjariya

Reputation: 543

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

final Color? bgColor;

Upvotes: 0

Related Questions