dart – 带有const关键字的Flutter变量

dart – 带有const关键字的Flutter变量,第1张

概述参见英文答案 > What color system does flutter use and why do we use `const Color` instead of `new Color`                                    2个 在Flutter文档的“编写你的第一个应用程序”教程中,步骤4标题为“步骤4:创建无限滚动ListView”,系统会要求您创建 参见英文答案 > What color system does flutter use and why do we use `const Color` instead of `new Color`                                    2个
在Flutter文档的“编写你的第一个应用程序”教程中,步骤4标题为“步骤4:创建无限滚动ListVIEw”,系统会要求您创建2个变量

class RandomWordsstate extends State<RandomWords> {  final _suggestions = <WordPair>[];  final _biggerFont = const TextStyle(FontSize: 18.0);  ...}

为什么在第3行使用const关键字?我来自C#和JavaScript背景,我不习惯在赋值语句的右侧看到这个.我注意到如果我删除它仍然按照我的预期工作.请你用拉面条说明为什么要使用它,我什么时候应该这样做?我猜这太过分了,我不必使用它,但我只是想确定一下.

我不相信这是重复的,因为这篇文章中的答案非常适合解释我的问题而在其他帖子中找不到,更不用说其他帖子是一个两部分问题,没有人会在使用谷歌时发现.

解决方法 来自dart新闻网站:

const” has a meaning that’s a bit more complex and subtle in Dart.
const modifIEs values. You can use it when creating collections,
like const [1,2,3],and when constructing objects (instead of new)
like const Point(2,3). Here,const means that the object’s entire
deep state can be determined entirely at compile time and that the
object will be froZen and completely immutable.

Read more here.

在我看来,你可以使用const构造函数(定义为const的构造函数),如const Text()或new Text().

如果你使用const Text():这将只分配一个内存空间,当你添加另一个const Text()时,它将重用相同的对象,但新的Text()将始终分配新的内存空间.因此,使用const可以提高程序性能(不是那么多性能,而是内存分配更少).此外,如果需要重用,可以将类构造函数定义为const.

I notice if I remove it it still works as I expected.

因为在创建对象/实例时,Dart有两个new和const关键字可选,它将由Dart VM处理.最初有一些问题,但现在已经解决了.

即使你避免使用const / new那些将由Dart VM添加.这两个关键字可选的原因是Flutter你必须在任何地方输入这两个(例如:在小部件树中).

Dart two enhancement() Feb 23

总结

以上是内存溢出为你收集整理的dart – 带有const关键字的Flutter变量全部内容,希望文章能够帮你解决dart – 带有const关键字的Flutter变量所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/web/1000603.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存