对于哪些flutter小部件,我们需要使用const? [英] For which flutter widgets we need to use const?

查看:350
本文介绍了对于哪些flutter小部件,我们需要使用const?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解 const 的好处,并且这些小部件将不会根据状态变化进行重建,但是当您看到下面的代码时,它们仍然是常量,我仍然很明显,我希望颤振自动处理。或者,颤振已经在照顾它了,我不知道吗?

I understand the benefits of const and the widgets will not rebuilt on state change, but still it's so obvious when you see below code that they are constants and I was hoping flutter handled it automatically. Or, flutter is taking care of it already and I am unaware?

// This makes sense to me but with above mentioned concern 
const Text('Your Text Here')
const Icon(Icons.chevron_right, size: 20.0),

无论如何,我的问题是:定义 SizedBox & EdgeInsets 小部件作为如下定义的常量(const)?

Anyhow, my question is: Is it fine to define SizedBox & EdgeInsets widgets as constants(const) as it defined below?

Padding(
  padding:
      const EdgeInsets.only(top: 16.0, right: 6.0, bottom: 16.0, left: 16.0),
  child: Row(
    children: <Widget>[
      const SizedBox(width: 16.0),
      const Icon(Icons.chevron_right, size: 20.0),
    ],
  ),
),


推荐答案

基本上是颤抖地试图更新树中的某些小部件,如果有的话const,没有任何更新。在这里您可以找到解释。
https://dev.to/pedromassango/flutter -performance-tips-1-const-constructors-4j41

Basically flutter trying to update some widgets in tree, and if it const, nothing to update. Here you can find explanation. https://dev.to/pedromassango/flutter-performance-tips-1-const-constructors-4j41

您需要了解一件重要的事情,即如果您更改树中的小部件,之后,该小部件将被删除并重新绘制(未更新)。因此,如果将其定义为const,则不会删除任何内容。没关系(关于您的问题的答案)
我也建议您阅读如何重新构建屏幕并更新窗口小部件:
https://www.didierboelens.com/2019/09/flutter-internals/

You need to know one an important thing, that if you changed widget in a tree, everything after this widget will be removed and redrawed(not updated). So, if you define it as const, nothing will be removed. And that is OK(answer on you question) Also I recommend to read how flutter rebuild screen and update widgets: https://www.didierboelens.com/2019/09/flutter-internals/

关于性能的最后一篇很棒的文章
https:// api。 flutter.dev/flutter/widgets/StatefulWidget-class.html#performance-considerations

And the last great article about performance https://api.flutter.dev/flutter/widgets/StatefulWidget-class.html#performance-considerations

这篇关于对于哪些flutter小部件,我们需要使用const?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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