Null safety and Maps

Viewed 3776

How do you handle the following case:

void main() {
  print(getInt('d'));
}

Map<String, int> myMap = {'a':1, 'b':2, 'c':3};

int getInt(String key) {
  if (!myMap.containsKey(key)) {
    myMap[key] = 0;
  }
  return myMap[key]!; 
}

myMap[key] is never null, but if I remove the ! of return myMap[key]!; I get the null safety error:

A value of type 'int?' can't be returned from the function 'getInt' because it has a return type of 'int'.

Is it proper to cast away the nullability with !, or is there a cleaner way?

3 Answers

Not sure what cleaner means, and the ! does exist for a reason.

You could simplify that if statement to a single line:

int getInt(String key) {
  myMap[key] ??= 0;
  return myMap[key]!; 
}

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.

Map<String, int> map = {'a': 1};
int i = map['a']; // Error

Solutions:

  • Use ?? and provide a default value.

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

    int i = map['a']!;
    

There is no way you can get rid of the bang when you're using a map.

This might be a cleaner way to code the same thing.

int getInt(String key) => myMap[key] ?? 0;
Related