When you use Colors.blue, for example this returns a constant Color object, but if you choose to use a shade instead, i.e. Colors.blue[300], then this object is NOT constant. This is important, for example, when you have a method that takes an optional Color parameter, whose default value must be constant. So how do we make a Color shade constant?
static const Color mainColor = Colors.blue \\All good!
static const Color shade = Colors.blue[400] \\ERROR: Const variables must be initialized with a constant value
So how do we make a Color shade constant?
You can't. To choose a specific shade, you should use the []
operator, which is just like calling a method, and since the value a method returns varies on runtime, the value returned from a method call cannot be use as constant.
This is important, for example, when you have a method that takes an optional Color parameter, whose default value must be constant.
If your situation is as simple as this one, just use the real value of Colors.blue[400]
, which is Color(0xFF42A5F5)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With