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?