dart - 对不可为空的变量使用late关键字有什么好处?

标签 dart

我看到的好处之一是(来自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/

相关文章:

Flutter Doctor找不到Android SDK,但一切都设置好了

flutter - 错误:未为类 'signInWithPhoneNumber'定义方法 'FirebaseAuth'

flutter - 为什么此警报对话框无法正常工作

Dart/Flutter - Flutter - 为什么 ListView 会无限大

Angular2 Dart 英雄之旅 : uppercase

flutter - 如何在flutter中将小部件屏幕截图存储为jpg文件?

dart - 匿名函数的返回类型

firebase - Firebase for Flutter 中此身份验证背后的逻辑是什么?

flutter - 在 Flutter 中使用 listView 的规则

unit-testing - 如何在 Flutter 中使用compute() 测试函数?