'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] ?
Solution 1:[1]
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
Solution 2:[2]
The problem is with null values. You need to define bgColor with nullable type
final Color? bgColor;
Solution 3:[3]
You can use (!) operator:
this.bgColor = Colors.grey[200]!
OR
use shade on the Color:
this.bgColor = Colors.grey.shade200
Solution 4:[4]
You are reading Map, which Color can't process it.
Instead, use Colors.grey.shade200 or Color(0xFFEEEEEE)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ravindra S. Patil |
| Solution 2 | Harsh Kanjariya |
| Solution 3 | gretal |
| Solution 4 | mitchiri_neko |
