gpt4 book ai didi

flutter - 如何检查 'late' 变量是否在 Dart 中初始化

转载 作者:行者123 更新时间:2023-12-03 23:58:11 111 4
gpt4 key购买 nike

在 kotlin 中,我们可以检查 'late' 类型变量是否像下面这样初始化

lateinit var file: File    
if (this::file.isInitialized) { ... }
有可能在 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 orassigned to. If you access it, it either immediately runs theinitializer (if it has one) or throws an exception. Sometimes you havesome state that’s lazily initialized where late might be a good fit,but you also need to be able to tell if the initialization hashappened yet.

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

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


https://dart.dev/guides/language/effective-dart/usage#avoid-late-variables-if-you-need-to-check-whether-they-are-initialized

关于flutter - 如何检查 'late' 变量是否在 Dart 中初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67197902/

111 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com