当尝试对一个可空map对象取值时,便会得到以下错误:
The method ‘[]’ can’t be unconditionally invoked because the receiver can be ‘null’.
Try making the call conditional (using ‘?.’) or adding a null check to the target (‘!’).
Map? a = {"name": "xxx"};
main () {
print(a["name"]); // 错误写法
}
dart原生没有valueOf
语法,无法通过map?.valueOf(key)
取值;
当然,也没这种写法map?[key]
。
正确的书写方法为:
(map??const{})[key]
,其中常量空mapconst{}
避免每次新建map,以节省资源开销
Map? a = {"name": "xxx"};
main () {
print((a??const {})["name"]);
}