gpt4 book ai didi

flutter - 确定要在Dart/Flutter中添加const的对象层次结构中的哪个级别

转载 作者:行者123 更新时间:2023-12-03 03:33:09 32 4
gpt4 key购买 nike

在小部件层次结构中,应该如何确定应该在哪个级别添加const?例如,如下:

const Padding(
padding: EdgeInsets.symmetric(
horizontal: LayoutStyles.horizontalPagePadding
),
child: Icon(Icons.search, color: Colors.black),
)
比说:
Padding(
padding: const EdgeInsets.symmetric(
horizontal: LayoutStyles.horizontalPagePadding
),
child: const Icon(Icons.search, color: Colors.black),
)
如果是这样,为什么?它是否取决于程序中最有可能出现哪些元素并因此被规范化?

最佳答案

取决于窗口小部件树的特定部分在整个应用程序生命周期中是恒定的。就像整个Padding小部件一样,它不会随着时间的推移而改变,因此使其成为常量。如果 child 或子树要更改,则第二种方法适合
来自文档-Performance considerations

If a subtree does not change, cache the widget that represents thatsubtree and re-use it each time it can be used. It is massively moreefficient for a widget to be re-used than for a new (butidentically-configured) widget to be created. Factoring out thestateful part into a widget that takes a child argument is a commonway of doing this.

Use const widgets where possible. (This is equivalent to caching awidget and re-using it.)


medium article on Inherited Widgets的摘录

Use const to build your widgets

Without const, selective rebuilding ofthe sub-tree does not happen. Flutter creates a new instance of eachwidget in the sub-tree and calls build() wasting precious cyclesespecially if your build methods are heavy.

关于flutter - 确定要在Dart/Flutter中添加const的对象层次结构中的哪个级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62608868/

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