我看到的好处之一是(来自here)
The runtime lazily initializes the late variable. For example, if a non-nullable instance variable must be calculated, adding the late modifier delays the calculation until the first use of the instance variable.
但是,当我尝试在代码中实现这一点时:
late int realInt;
void main() {
calculate();
print(realInt);
}
void calculate() => Future.delayed(Duration(seconds: 1), () => realInt = 1);
它给我一个错误Error: LateInitializationError: Field 'realInt' has not been initialized.
那么,如果延迟过程不能单独发挥作用,那么文档中提到的那一行是什么意思呢?
最佳答案
尝试看下面的例子:
void main() {
final a = A(5);
print('Before fetching realInt');
print(a.realInt);
print('After fetching realInt');
print(a.realInt);
print('After another fetching realInt');
}
class A {
final int value;
late int realInt = calculate();
A(this.value);
int calculate() {
print('Some hard work...');
return value*value;
}
}
输出:Before fetching realInt
Some hard work...
25
After fetching realInt
25
After another fetching realInt
如您所见,这里的late
关键字的使用更像是一个懒惰的评估值,该值将在首次使用时首先进行计算。这等于我们今天对静态变量(也可以进行延迟评估)的行为,但是对于late
,我们现在可以对类成员变量执行相同的操作。late
也可用于指示变量将在使用前初始化,这是您在示例中所做的。但是由于代码的异步工作方式,您最终尝试在将值设置为任何会引发Exception
的值之前获取该值。因此,不能将
late
用作Future
的替代方法。
关于dart - 对不可为空的变量使用late关键字有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63375445/