Null safety and Maps

2,393

Solution 1

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

Solution 2

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']!;
    

Solution 3

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;
Share:
2,393
Thierry
Author by

Thierry

I graduated in Computer Science and Engineering at UCLouvain. I worked as a software engineer and product manager for the worldwide Digital Security Company, GEMALTO (now part of THALES Group) for almost a decade before becoming an entrepreneur in China, where QR Codes are mainstream business and personal tools. Now back in Belgium, I use my experience as an entrepreneur and focus on the marketing success of companies based on information technology.

Updated on December 28, 2022

Comments

  • Thierry
    Thierry over 1 year

    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?

  • Ivo
    Ivo over 2 years
    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;
  • Christopher Moore
    Christopher Moore over 2 years
    @IvoBeckers Nice! That looks even "cleaner".