我有类似于这个示例代码的代码(别介意它没有意义):
void foo(Map<int, String> myMap) {
String s = myMap[1];
}
Dart 分析器警告我关于 String s = myMap[1];
行带有以下警告:A value of type 'String?' can't be assigned to a variable of type 'String'. Try changing the type of the variable, or casting the right-hand type to 'String'.
我看到这是因为从 map 中检索值可能会导致
null
.为什么以下代码段给我同样的警告?void foo(Map<int, String> myMap) {
if (myMap.containsKey(1)) {
String s = myMap[1];
}
}
最佳答案
问题:
来自 docs :
The index [] operator on the Map class returns null if the key isn’t present. This implies that the return type of that operator must be nullable.
看看下面的代码。自键
b
Map
中缺少, map['b']
返回 null
并将其值赋给 int
会引起 runtime
如果这通过了静态分析,则会出错。Map<String, int> map = {'a': 1};
int i = map['b']; // Error: You can't assign null to a non-nullable field.
解决方案:
??
并提供默认值(推荐)int i = map['b'] ?? 0;
!
运算符(operator)。int i = map['b']!; // Caution! It causes runtime error if there's no key.
关于Dart 空安全 - 以空安全方式从 map 中检索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65235879/