Is there an easy way to add Const as much as possible in Flutter?
Solution 1
It's actually quite simple. You should open analysis_options.yaml and then under linter specify the required rules.
...
linter:
rules:
- prefer_const_declarations
You can check the rules here: https://dart-lang.github.io/linter/lints/index.html
Solution 2
In addition to linting, you can fix most cases of missing or redundant const automatically by running dart fix --apply
. Run dart fix --dry-run
first to see what will change.
Comments
-
yellowgray over 1 year
I have read the article here about Final and 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).
Is there any easy way let the IDE plugin/lint add const Widget/Variable as much as it can automatically? Or give some hint like
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.
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 ...