如何检查'late'变量是否在Dart中初始化 [英] How to check 'late' variable is initialized in Dart

查看:296
本文介绍了如何检查'late'变量是否在Dart中初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在科特林,就像下面的

lateinit var file: File    

if (this::file.isInitialized) { ... }

我正在寻找Dart中类似的东西.

I am looking for something similar in Dart.

推荐答案

不幸的是,这不可能.

从文档中

避免后期变量,如果您需要检查它们是否已初始化.

Dart无法提供任何方法来判断后期变量是否已初始化或分配给.如果您访问它,它将立即运行初始化程序(如果有的话)或引发异常.有时候你有有些状态是懒洋洋地初始化的,而迟到可能是一个很好的选择,但您还需要知道初始化是否具有发生了.

AVOID late variables if you need to check whether they are initialized.

Dart offers no way to tell if a late variable has been initialized or assigned to. If you access it, it either immediately runs the initializer (if it has one) or throws an exception. Sometimes you have some state that’s lazily initialized where late might be a good fit, but you also need to be able to tell if the initialization has happened yet.

尽管您可以通过将状态存储在Late变量,并具有一个单独的布尔字段来跟踪是否该变量已设置,这是多余的,因为Dart在内部保持Late变量的初始化状态.相反, 通常更清晰,使变量为非晚期且可为空.然后你 可以通过检查是否为空来查看变量是否已初始化.

Although you could detect initialization by storing the state in a late variable and having a separate boolean field that tracks whether the variable has been set, that’s redundant because Dart internally maintains the initialized status of the late variable. Instead, it’s usually clearer to make the variable non-late and nullable. Then you can see if the variable has been initialized by checking for null.

当然,如果null是该变量的有效初始化值,则拥有一个单独的布尔字段可能确实有意义.

Of course, if null is a valid initialized value for the variable, then it probably does make sense to have a separate boolean field.

https://dart.dev/guides/language/efficiency-dart/usage#avoid-late-variables-if-you-需要检查它们是否已初始化

这篇关于如何检查'late'变量是否在Dart中初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆