I had code similar to this example code (never mind that it makes no sense):
void foo(Map<int, String> myMap) {
String s = myMap[1];
}
The dart analyzer warns me about the line String s = myMap[1];
with the following warning:
A value of type 'String?' can't be assigned to a variable of type 'String'. Try changing the type of the variable, or casting the right-hand type to 'String'.
I see that this is happening because retrieving a value from a map can result in null
. Why does the following snippet give me the same warning?
void foo(Map<int, String> myMap) {
if (myMap.containsKey(1)) {
String s = myMap[1];
}
}
Problem:
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.
Take a look at the following code. Since the key b
is missing from the Map
, map['b']
returns null
and assigning its value to int
would have caused runtime
error if this had passed the static analysis.
Map<String, int> map = {'a': 1};
int i = map['b']; // Error: You can't assign null to a non-nullable field.
Solutions:
Use ??
and provide a default value (recommended)
int i = map['b'] ?? 0;
Use the Bang !
operator.
int i = map['b']!; // Caution! It causes runtime error if there's no key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With