您如何处理以下情况:
void main() {
print(getInt('d'));
}
Map<String, int> myMap = {'a':1, 'b':2, 'c':3};
int getInt(String key) {
if (!myMap.containsKey(key)) {
myMap[key] = 0;
}
return myMap[key]!;
}
myMap[key]
永远不会为空,但如果我删除 !
的 return myMap[key]!;
我得到空安全错误:A value of type 'int?' can't be returned from the function 'getInt' because it has a return type of 'int'.
用
!
抛弃可空性是否合适? ,或者有更干净的方法吗?
最佳答案
不知道清洁剂是什么意思,还有 !
存在是有原因的。
您可以将 if 语句简化为一行:
int getInt(String key) {
myMap[key] ??= 0;
return myMap[key]!;
}
关于flutter - 空安全和 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66603650/