Dart 空安全 - 以空安全方式从 map 中检索值

标签 dart dart-null-safety

我有类似于这个示例代码的代码(别介意它没有意义):

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;
    
  • 使用 Bang ! 运算符(operator)。
    int i = map['b']!; // Caution! It causes runtime error if there's no key.
    
  • 关于Dart 空安全 - 以空安全方式从 map 中检索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65235879/

    相关文章:

    dart - 在 Dart 中,如何在断言失败时打印消息?

    flutter - 如何在 flutter 中使用选定的键和值从 map 列表创建 map

    flutter - 与参数类型 'Object' 相关的错误无法分配给参数类型 'ImageProvider<Object>?'

    flutter - 空安全和 map

    dart - 模板重复不适用于嵌套列表(Polymer.dart)

    asynchronous - Flutter - 如何从 Firestore 返回当前用户

    flutter - TabBar和AppBar冲突

    flutter - 如何使用 dart null-safety 对可能包含空值的列表进行排序

    flutter - 如何构建具有空安全性的空工厂构造函数?

    flutter - Dart/Flutter 将分数字符串转换为 double 字符串