
7

关于 dart 中的 late 关键字,你了解多少?
source link: https://www.techug.com/post/how-much-do-you-know-about-the-late-keyword-in-dart.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

作者:坚果
公众号:”大前端之旅”
华为云享专家,InfoQ 签约作者,阿里云专家博主,51CTO 博客首席体验官,开源项目GVA成员之一,专注于大前端技术的分享,包括 Flutter,小程序,安卓,VUE,JavaScript。
Dart 2.12 在变量中添加了 late 修饰符。这可以用于以下两种情况。
-
将您的项目迁移到零安全。
-
延时初始化一个变量。
1. 将您的项目迁移到零安全
在声明初始化的不可为空变量时可以使用late
修饰符。
late String title; void getTitle(){ title = 'Default'; print('Title is $title'); }
在使用变量之前的后期确保变量稍后必须初始化。否则在使用变量时可能会遇到运行时错误。
2.延时初始化一个变量
这种延时初始化在以下情况下很方便。
-
该变量可能不需要,并且初始化它的成本很高。
-
您正在初始化一个实例变量,它的初始化程序需要访问它。
// This is the program's only call to _getResult(). late String result = _getResult(); // Lazily initialized.
在上面的示例中,如果从未使用过变量,则永远不会调用成本更高的 _getResult() 函数。
假设_getResult()
是计算该结果的非常重要的函数。但是,如果我们将它分配给任何变量而不延时,那么_getResult()
即使我们不使用它,每次都会执行。
没有 late 关键字
//START String result = _getResult(); //END
在上面的代码中,result 从未使用过,但_getResult()
依旧会被执行。
使用 late 关键字
//START late String result = _getResult(); //END
在上面的代码中_getResult()
没有被执行,因为变量 result 从未使用过发现了没,它是使用 late 修饰符声明的。
好的,关于late
关键字,我们就了解到这儿,这也是对自己的知识体系的一个梳理,如果你觉得还不错的话,可以点赞支持一下,谢谢。
本文文字及图片出自 InfoQ
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK