简体   繁体   English

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

[英]Is there an easy way to add Const as much as possible in Flutter?

I have read the article here about Final and Const .我在这里阅读了有关Final 和 Const的文章。 I also saw many example code from flutter team use many const as they can (just read the example of todos list from package river_pod), and some article about how compile-time constant widget good for performance ( like this ).我还看到了 Flutter 团队的许多示例代码尽可能地使用了许多const (只需阅读包 river_pod 中的todos 列表示例),以及一些关于编译时常量小部件如何提高性能的文章( 比如这个)。

Is there any easy way let the IDE plugin/lint add const Widget/Variable as much as it can automatically?有没有什么简单的方法让 IDE 插件/lint 尽可能多地自动添加 const Widget/Variable? Or give some hint like This Widget/Variable' is better to use with const .或者给出一些提示,例如This Widget/Variable' is better to use with const

I checked the lint package here and read Effective Dart:Style , but didn't see any information about it.我在这里检查了lint 包并阅读了Effective Dart:Style ,但没有看到任何关于它的信息。

Thanks for help!感谢帮助!

I add some example cases:我添加一些示例案例:

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'),
    )
    ...

or even a class甚至一堂课

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

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

It's actually quite simple.其实很简单。 You should open analysis_options.yaml and then under linter specify the required rules.您应该打开analysis_options.yaml ,然后在 linter 下指定所需的规则。

...
linter:
  rules:      
    - prefer_const_declarations

You can check the rules here: https://dart-lang.github.io/linter/lints/index.html你可以在这里查看规则: https : //dart-lang.github.io/linter/lints/index.html

In addition to linting, you can fix most cases of missing or redundant const automatically by running dart fix --apply<\/code> .除了 linting 之外,您还可以通过运行dart fix --apply<\/code>来自动修复大多数丢失或冗余 const 的情况。 Run dart fix --dry-run<\/code> first to see what will change.先运行dart fix --dry-run<\/code>看看会发生什么变化。

"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM