有没有一种简单的方法可以在 Flutter 中尽可能多地添加 Const?

yel*_*ray 1 performance dart flutter

我在这里阅读了关于Final 和 Const的文章。我还看到Flutter团队的许多示例代码尽可能多地使用const(只需阅读包 river_pod 中的todos 列表示例),以及一些关于编译时常量小部件如何提高性能的文章(像这样)。

有没有什么简单的方法可以让 IDE 插件/lint 尽可能多地添加 const Widget/Variable?或者给出一些提示,比如This Widget/Variable' is better to use with const

我在这里检查了lint 包并阅读了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'),
    )
    ...
Run Code Online (Sandbox Code Playgroud)

甚至一个班级

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

class Toolbar extends HookWidget {
  const Toolbar({Key key}) : super(key: key); //here
  ...
Run Code Online (Sandbox Code Playgroud)

rjh*_*rjh 10

除了 linting 之外,您还可以通过运行来自动修复大多数缺失或冗余 const 的情况dart fix --apply。首先运行dart fix --dry-run看看会发生什么变化。


小智 5

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

...
linter:
  rules:      
    - prefer_const_declarations
Run Code Online (Sandbox Code Playgroud)

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

  • 你的回答很封闭,但不适合我的情况。我发现我正在寻找的 **lint 规则** 是 `prefer_const_constructors` 和 `prefer_const_constructors_in_immutables`。问题解决了!谢谢 (2认同)