If you take a look at the documentation of the []
operator on Map
:
V? operator [](
Object? key
)
V?
here means that the type of the value V
will always be nullable. The reason for this is because of the following detail for this operator:
The value for the given key
, or null
if key
is not in the map.
https://api.dart.dev/stable/2.18.1/dart-core/Map/operator_get.html
So the reason for your error is because your code is not prepared for the case of []
returns null
in case the key are not in your Map
.
There are multiple solutions for this problem which depends on how sure you are about the specific piece of code and what behavior you want in case of failure.
If you are e.g. completely sure that curr
will always point to a valid key in the Map
you can do: scarScore[curr]!
(notice the !
). This will add a runtime null-check and crash your application in case the value from the []
operator ends up being null
.
Alternative, if you expect some keys to not be in the Map
, you can provide default values like prev + (scarScore[curr] ?? 0)
where null
will then be assumed to be translated to the value 0
.
For a detailed explanation for why the []
operator are nullable, you can read: https://dart.dev/null-safety/understanding-null-safety#the-map-index-operator-is-nullable