【发布时间】:2021-03-16 18:59:33
【问题描述】:
我正在尝试将一些代码迁移到启用 null 安全性的 Dart 2.12,但在找到迁移具有延迟加载/缓存值的方法的好方法时遇到了问题。
Dart 2.12 不会编译以下代码,除非我将 getValue() 的返回类型从 MyObject 更改为 MyObject?。但是getValue() 永远不会返回null。
class MyObject {
// ...
}
MyObject? _cachedValue;
MyObject getValue() {
if (_cachedValue == null) {
_cachedValue = MyObject();
// some heavy computing...
}
return _cachedValue;
}
2021 年 3 月 17 日更新
根据stephen 的回答和Mattia 的评论,我现在正在使用:
class MyObject {
// ...
}
MyObject _computeValue() {
MyObject obj = MyObject();
// some heavy computing...
return obj;
}
late final MyObject cachedValue = _computeValue();
【问题讨论】:
-
使用 nnbd 进行延迟初始化,您可以使用
late final例如。late final cachedVaue = getValue()和getValue只会在第一次调用cachedValue时调用一次。
标签: dart dart-null-safety