Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart null safety - retrieving value from map in a null safe way

I had code similar to this example code (never mind that it makes no sense):

void foo(Map<int, String> myMap) {
  String s = myMap[1];
}

The dart analyzer warns me about the line String s = myMap[1]; with the following warning:

A value of type 'String?' can't be assigned to a variable of type 'String'. Try changing the type of the variable, or casting the right-hand type to 'String'.

I see that this is happening because retrieving a value from a map can result in null. Why does the following snippet give me the same warning?

void foo(Map<int, String> myMap) {
  if (myMap.containsKey(1)) {
    String s = myMap[1];
  }
}
like image 695
SebastianJL Avatar asked Dec 17 '22 12:12

SebastianJL


1 Answers

Problem:

From the docs:

The index [] operator on the Map class returns null if the key isn’t present. This implies that the return type of that operator must be nullable.

Take a look at the following code. Since the key b is missing from the Map, map['b'] returns null and assigning its value to int would have caused runtime error if this had passed the static analysis.

Map<String, int> map = {'a': 1};
int i = map['b']; // Error: You can't assign null to a non-nullable field.

Solutions:

  • Use ?? and provide a default value (recommended)

    int i = map['b'] ?? 0;
    
  • Use the Bang ! operator.

    int i = map['b']!; // Caution! It causes runtime error if there's no key.
    
like image 70
CopsOnRoad Avatar answered Jan 11 '23 23:01

CopsOnRoad