Search code examples
dartdart-null-safety

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];
  }
}

Solution

  • The warning is based entirely on the type of the operation. The operator [] of a Map<K,V> returns a V?, so it might be null. The type system doesn't know whether the key is in the map or not, or even what a map is.

    That you call another method which implies that the return value won't be null doesn't change the type, and the compiler doesn't get that implication.