【问题标题】:Is there an easy way to add Const as much as possible in Flutter?有没有一种简单的方法可以在 Flutter 中尽可能多地添加 Const?
【发布时间】:2021-02-19 05:16:25
【问题描述】:

我在这里阅读了有关Final and Const 的文章。我还看到 Flutter 团队的许多示例代码尽可能地使用了许多 const(只需阅读来自包 river_pod 的 todos list 的示例),以及一些关于如何编译时常量小部件 有利于性能 (like this)。

是否有任何简单的方法让 IDE 插件/lint 尽可能多地自动添加 const Widget/Variable?或者给一些提示,比如This Widget/Variable' is better to use with const

我在这里查看了lint package 并阅读了Effective Dart:Style,但没有看到任何相关信息。

感谢您的帮助!

我添加一些例子:

ListView(
  padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 40), // here
  children: [ ...
    const SizedBox(height: 42), //here
    const Image( //here
      width: 100,
      height: 100,
      image: AssetImage('assets/logo.png'),
    )
    ...

甚至是一个班级

Container(
  child: const Toolbar(), //here
...

class Toolbar extends HookWidget {
  const Toolbar({Key key}) : super(key: key); //here
  ...

【问题讨论】:

    标签: performance flutter dart


    【解决方案1】:

    其实很简单。您应该打开 analysis_options.yaml,然后在 linter 下指定所需的规则。

    ...
    linter:
      rules:      
        - prefer_const_declarations
    

    您可以在这里查看规则:https://dart-lang.github.io/linter/lints/index.html

    【讨论】:

    • 感谢您的回答。我已经尝试了您的建议,但没有注意到 Lint 中已经存在一些持续检查。 dart.dev/guides/language/…。但是我仍然有疑问,我上面提供的示例似乎没有被检测到。我的例子不支持prefer_const_declarations检查吗?
    • 问题是,在您提供的情况下,分析器可能永远无法知道您的意图。标有 const 的值将在运行时进行重复数据删除,分析器永远不知道您是否会使用该属性。必须由作者明确完成。
    • 也就是说,我提供的例子应该由作者经验处理?我认为我提供的示例是分析器可能有机会检测到的简单案例。如果一些我没有考虑过的权衡案例?或者我对使用 const 关键字有什么误解?
    • 你的回答太封闭了,但不适合我的情况。我发现我正在寻找的 lint 规则prefer_const_constructorsprefer_const_constructors_in_immutables。问题解决了!谢谢
    • 是否有任何脚本可以自动执行此操作?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-18
    • 2011-03-08
    • 1970-01-01
    相关资源
    最近更新 更多