1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

DartのMap型でkeyからvalueを取るとNull許容型になる挙動を回避する方法

Posted at

概要

DartのMap型Map<type, type>を使う場合、何らかのkeyからvalueを取る場面がある。既定では取得したvalueはNull許容型になる。これを回避するためには??演算子を使って、nullだった場合のデフォルト値を定義する。

課題

以下のコードではint型の変数appleNumに、int?型となったfruits["apple"]を代入しようとしているため警告が発生する。

example.dart
Map<String, int> fruits = {"apple": 1, "banana": 3};
int appleNum = fruits["apple"]; // 警告発生

原因

これはMap型の挙動で、指定されたkeyがない場合はnullを返す。
そのためMap<type, type>[key]で返されるvalueの型はtype?となる。

example.dart
Map<String, int> fruits = {"apple": 1, "banana": 3};
// fruits["apple"] -> 1
// fruits["strawberry"] -> null

回避策

??(Null合体演算子)を使用して、nullが返された場合に代入するデフォルト値を設定する。

以下の例ではstrawberryというkeyはないが、??演算子でnullの代わりに0を代入する。このようにすることで、nullが変数に代入されなくなるためtype?ではなくtypeを使える。

example.dart
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?

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?