5

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?

Thierry
  • 7,775
  • 2
  • 15
  • 33

3 Answers3

3

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]!; 
}
Christopher Moore
  • 15,626
  • 10
  • 42
  • 52
  • fyi, assignments in dart also return the value, and then it's even smart enough here to know it's not null. so you could simplify it even more by saying `return myMap[key] ??= 0;` – Ivo Mar 24 '22 at 13:07
  • @IvoBeckers Nice! That looks even "cleaner". – Christopher Moore Mar 24 '22 at 13:17
3

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']!;
    
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
1

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;
Suman Maharjan
  • 1,070
  • 7
  • 14