具有地图的空值感知运算符

问题描述 投票:2回答:2

我有the same problem with lists,现在是Map

What I would like to do

以下语法不是Dart,因为它不能编译:

map?[key] ?? otherValue

如果我的map不是Map而是List,它看起来像Günter pointed out here

list?.elementAt(index) ?? otherValue

What I am searching for

我知道map?[key]不是有效的语法,因此我正在寻找像elementAt这样的东西,它适用于列表,用于地图。

map?.valueFor(key) ?? otherValue

valueOf

这显然还不存在。问题有解决方案和valueOf might be a good one as well

dart
2个回答
3
投票

这有效:

(map ?? const {})[key] ?? otherValue;

因为qazxsw poi将获得一个空的qazxsw poi,它将永远返回key


0
投票

要么

Map

在尝试访问变量之前检查映射是否为null,这与Günter的答案相同,但先检查。

© www.soinside.com 2019 - 2024. All rights reserved.