Here is how you add and use linters in your Flutter app to enhance and maintain higher code quality.
With linters and linting rules, you can verify clean code principles and maintain high code quality during the development process of your Flutter app. A linter is a tool that analyzes source code to detect and report potential errors or issues.
When you use a code editor like VSCode or Android Studio and you build your project, a static code analysis is executed to ensure, the code is free of compile errors. It uses the dart analyze command internally. On top of that, you can include additional rules with custom linters.
Here is how you set them up in a Flutter project.
To add a package of linter rules like flutter_lints, execute the command
flutter pub add flutter_lints --dev. In your
pubspec.yaml you’ll notice a new entry in the section
analysis_options.yaml file (create an empty file if you don’t have it) and include the package with
You can also copy the content of the analysis file of the package into your
analysis_options.yaml file if you want to manage everything yourself.
To disable specific rules, open
analysis_options.yaml, add a line with the rule name in the rules section, and give it the keyword
false. Make sure to use the correct indentation!
To enable specific rules that are disabled by default, add a new line and use the keyword
true after the rule name. Here is a small demo video of how Visual Studio Code immediately handles changes of linter rules.
To learn more about linter rules, check the official documentation.
The default ruleset shipped with every Flutter app created after version 2.3. It contains 13 rules. It’s suited best for Flutter apps. In most cases, you will be fine with these rules.
An alternative to lints with around 200 rules but nearly half of them are deactivated by default. If you want to dive deep into linting without writing your own rules, you can experiment with these to get going.
In this article, we learned that linters are tools that can help developers write better code by detecting and reporting potential issues or errors. In addition, you should now be able to add linter packages and manage rules in your Flutter project.