Introduction
Here is how you add and use linters in your Flutter app to enhance and maintain higher code quality. Customize them to your needs!
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.
🔔 Hint
Usually, you should be fine with the default settings of a Flutter project.
Setup
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 dev_dependencies
.
Open your analysis_options.yaml
file (create an empty file if you don’t have it) and include the package with include: package:flutter_lints/flutter.yaml
.
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.
Want More Flutter Content?
Join my bi-weekly newsletter that delivers small Flutter portions right in your inbox. A title, an abstract, a link, and you decide if you want to dive in!
To learn more about linter rules, check the official documentation.
Popular linters
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.
➡ lints
Official linting recommendations by the Flutter and Dart team. It has 2 sets of linters: Core (around 30 rules) and Recommended (around 55 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.
Conclusion
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.