1

If I have a map like:

Map<String, int> myMap = Map();

Add a key and value:

myMap.putIfAbsent("yolo", 1000);

Then add a number using an operator like +=

myMap["yolo"] += 100;

With null safety it throws an error saying

The method '+' can't be unconditionally invoked because the receiver can be 'null'.

In a map, what is the best way to set the value based on the key?

Matthew
  • 3,411
  • 2
  • 28
  • 28
  • This is https://github.com/dart-lang/language/issues/1113. You currently will need to do `myMap['yolo'] = myMap['yolo']! + 100;`. – jamesdlin Mar 13 '21 at 00:19

1 Answers1

2

This error is expected. If your map doesn't contain an entry with a key "yolo", then calling myMap["yolo"] += 100; would cause a runtime null error.

If 0 is a sensible "default value" for this context, you could write something like:

myMap["yolo"] = (myMap["yolo"] ?? 0) + 100;
cameron1024
  • 9,083
  • 2
  • 16
  • 36