此代码在没有空安全的情况下运行良好:
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)。
感谢您的帮助!
最佳答案
您可以选择以下方法之一:
- 显式定义
fold
方法类型参数:
var tot = x.fold<double>(0.0, (a, b) => a + b.dist);
- 显式定义
tot
变量类型:
double tot = x.fold(0.0, (a, b) => a + b.dist);
关于dart - 如何将列表字段迁移到空安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68051424/