我有the same problem with lists,现在是Map
。
以下语法不是Dart,因为它不能编译:
map?[key] ?? otherValue
如果我的map
不是Map
而是List
,它看起来像Günter pointed out here:
list?.elementAt(index) ?? otherValue
我知道map?[key]
不是有效的语法,因此我正在寻找像elementAt
这样的东西,它适用于列表,用于地图。
map?.valueFor(key) ?? otherValue
这显然还不存在。问题有解决方案和valueOf
might be a good one as well。
这有效:
(map ?? const {})[key] ?? otherValue;
因为qazxsw poi将获得一个空的qazxsw poi,它将永远返回key
。
要么
Map
在尝试访问变量之前检查映射是否为null,这与Günter的答案相同,但先检查。