dart - 如何将列表字段迁移到空安全

标签 dart dart-null-safety

此代码在没有空安全的情况下运行良好:

void main() {
  final a = X(22.5);
  final b = X(22.5);
  List<X> x = [a, b];
  var tot = x.fold(0.0, (a, b) => a + b.dist);
  print(tot);
}

class X {
  final double dist;
  X(this.dist);
}

有了空安全,我们得到:

不能无条件调用运算符“+”,因为接收者可以为“null”。 尝试向目标添加空检查(“!”)。

不知道目标是谁/什么,也不知道接收者是谁。我已经阅读了所有关于空安全的 Dart Material ,但无法将其构建为箭头表达式 (=> a + b.dist)。

感谢您的帮助!

最佳答案

您可以选择以下方法之一:

  1. 显式定义fold 方法类型参数:
var tot = x.fold<double>(0.0, (a, b) => a + b.dist);
  1. 显式定义 tot 变量类型:
double tot = x.fold(0.0, (a, b) => a + b.dist);

关于dart - 如何将列表字段迁移到空安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68051424/

相关文章:

dart - 如何传递消息来隔离和处理错误

flutter - 类型 'List<Widget?>' 不是类型转换中类型 'List<Widget>' 的子类型

dart-null-safety - 错误: The argument type 'List<int>' can't be assigned to the parameter type 'Uint8List'

flutter - Dart比较int null安全问题: operator can't be unconditionally invoked because the receiver can be 'null'

android - 使用 --no-sound-null-safety Flutter 生成 App Bundle

json - Flutter 迁移到 null 安全性,是迟到还是可为 null?

dart - 在 Dart 中动态填充父字段

dart - 糟糕的 PageView 性能

flutter - 在 SingleChildScrollView 内垂直居中小部件

flutter - 如何在Flutter中使用带标签的窗口小部件?