概要
DartのMap型Map<type, type>
を使う場合、何らかのkey
からvalue
を取る場面がある。既定では取得したvalue
はNull許容型になる。これを回避するためには??
演算子を使って、null
だった場合のデフォルト値を定義する。
課題
以下のコードではint型の変数appleNum
に、int?型となったfruits["apple"]
を代入しようとしているため警告が発生する。
Map<String, int> fruits = {"apple": 1, "banana": 3};
int appleNum = fruits["apple"]; // 警告発生
原因
これはMap型の挙動で、指定されたkey
がない場合はnull
を返す。
そのためMap<type, type>[key]
で返されるvalueの型はtype?
となる。
Map<String, int> fruits = {"apple": 1, "banana": 3};
// fruits["apple"] -> 1
// fruits["strawberry"] -> null
回避策
??
(Null合体演算子)を使用して、null
が返された場合に代入するデフォルト値を設定する。
以下の例ではstrawberry
というkey
はないが、??
演算子でnull
の代わりに0
を代入する。このようにすることで、null
が変数に代入されなくなるためtype?
ではなくtype
を使える。
Map<String, int> fruits = {"apple": 1, "banana": 3};
int appleNum = fruits["apple"] ?? 0; // appleNum = 1
int strawberryNum = fruits["strawberry"] ?? 0; // strawberryNum = 0
参考
質問:Dart null safety - retrieving value from map in a null safe way
質問者:SebastianJL
回答者:CopsOnRoad
参考にした回答:https://stackoverflow.com/a/67725900
How do I signal that the return value from a Map is non-nullable?