Add Lint Rules To A Flutter Application
In this article, we will see how to add our own linting rules to a Flutter application and how to use the flutter_lints package.
What Is Linting?
Linting is the process of analyzing a source code for any programming error, stylistic errors or any bug that can occur in the code. It is helpful, if you are working in a team, that way the whole team will follow some specific rules in the codebase.
For example:
As you can see in the image, we have a blue line under the MyHomePage
, this means that this is an informational message:
This class (or a class that this class inherits from) is marked as â@immutableâ, but one or more of its instance fields arenât final: MyHomePage.titledart(must_be_immutable)
In this case, you can still perform flutter run
, but it would be best to solve this issue, as those are the best practices that the Flutter team has added. The above message can be removed by making the title
field as final final String? title;
.
Add Lint Rules
To add your own lint rules, create a file called anaylsis_options.yaml
, then navigate to the following page: Linter For Dart. In this page you will find all the lint rules that you can add to anaylsis_options.yaml
. To add a lint rule, you can do the following:
This is the description of the above rule:
For example, if you do the following in the code:
You would get the following info message:
Avoid empty else statements.dart(avoid_empty_else)
You can also change the severity of the above rule by adding the following to the anaylsis_options.yaml
file:
There are 3 different severity level:
info : An informational message that doesnât cause analysis to fail. Example: dead_code
warning: A warning that doesnât cause analysis to fail unless the analyzer is configured to treat warnings as errors. Example: invalid_null_aware_operator
error: An error that causes analysis to fail. Example: invalid_assignment
You can also exclude some files by doing the following:
Using flutter_lints package
Instead of adding your own specific rules, you can just use a package that would have the recommended lint rules. For example the flutter_lints
package. To add it, open the pubspec.yaml
file and add it as a dev dependency:
Then use the include
option in the analysis_options.yaml
, to add the lint file of the flutter_lints
package:
You can check the rules here. The flutter_lints
also includes lint rules used in the lint package. If you want to disable a specific rule that is included inside the flutter_lints
package, then you can use lint_rule: false
as shown above with avoid_empty_else
.
Check here for more info: analysis-option
I hope you enjoyed reading this flutter tutorial, please feel free to leave any comments or feedback on this post!