Flutter null safety - The argument type 'Color?' can't be assigned to the parameter type 'Color'

3,772

Solution 1

You can use 0xFFE0E0E0 for grey[300].

To pick material colors you can use this tool.

To select a specific color from one of the swatches, index into the swatch using an integer for the specific color desired, as follows:

Color selection = Colors.green[400]!; // Selects a mid-range green.

Each ColorSwatch constant is a color and can used directly. For example:

Container(
  color: Colors.blue, // same as Colors.blue[500] or Colors.blue.shade500
)

Solution 2

Problem:

Color color = Colors.grey[300]; // Error in null-safe mode

When you use Colors.grey[300], you're actually getting the color from a Map which Dart (in null-safe mode) warns you about because that value could be null. See more


Solutions:

There are two solutions for it. One is general and one is only specific to this case.

  1. Use Bang operator (!)

    Color color = Colors.grey[300]!  // Added '!', error gone 
    
  2. Use shadeXXX on the Color

    Color color = Colors.grey.shade300;
    

Solution 3

use shade300 like Color color = Colors.grey.shade300;

Share:
3,772
AJ989
Author by

AJ989

Updated on December 06, 2022

Comments

  • AJ989
    AJ989 over 1 year

    I changed my SDK version for flutter to min , so that I can fix my code for null safety.

    There is one issue that I don't understand, this line produces the following error:

    The argument type 'Color?' can't be assigned to the parameter type 'Color'
    
    border: Border.all(color: Colors.grey[300], width: 1),
    

    but if I change Colors.grey[300] with whatever value that doesn't use [], it will work, so Colors.grey works perfectly fine.

    What should I change here to keep using grey[300]?

  • AJ989
    AJ989 over 3 years
    yeah I noticed that, but does this mean using specific shades of a color with [x] is not allowed anymore since null safety in flutter 2?
  • Simon Sot
    Simon Sot over 3 years
    Well yeah, you can check issue here github.com/flutter/flutter/issues/71591#issue-755539014
  • giorgio79
    giorgio79 almost 3 years
    Tried this, now I am getting "Invalid constant value"
  • CopsOnRoad
    CopsOnRoad almost 3 years
    @giorgio79 Although it is unrelated but what color are you using?
  • giorgio79
    giorgio79 almost 3 years
    Yeah, tried to use one of the shades. Turns out those are not constant, so have to use hex code Color(#123456...) lol. One of the bigger piles of dung in Flutter
  • CopsOnRoad
    CopsOnRoad almost 3 years
    @giorgio79 But my answer doesn't have to do anything with it. You must already be getting the same error before using this answer. For example: Colors.grey[300] was already a non-const in the first place.
  • Abdulhakim Zeinu
    Abdulhakim Zeinu about 2 years
    Some description on the first solution. Use Bang operator ! only if you're sure that the object will never evaluated to null