When you're starting a new project it's a pretty good idea to add linting rules immediately because they are useful and make the code you're writing more cohesive by giving you a nudge about best practices. Flutter is no exception to this, so I'm going to show you how to set up static analysis in a Flutter project.
The package I'm introducing is called
lint you can find it on pub.dev. You can use this package for both Dart and Flutter projects. To get things started you need to add the following line to your
Or alternatively use this command:
1flutter pub add lint
After that you need to create a file called
analysis_options.yaml in the your project's root directory. And you just need to add one line to it:
Note that if you're developing a package the author advises to use this instead:
And that's it. Once you save the file your IDE should pick up on the new changes and start showing you issues with your code. I personally use Visual Studio Code because I got sick of how much RAM Android Studio was eating.
For the purposes of this post I added
lint to an existing project(late is better than never right?). Like I wrote above, your IDE will analyze your source code and find areas that break the pre-defined set of linting rules. Here's what it looks like in VSCode(this is the 'Problems' Tab):
And you just basically have to go through each problem and solve it by changing your code. If you hover over the problematic code you can also see a short description and there is also a link to code examples.
As an example the link above shows the following page when you click through:
In my example above the red errors are ones that you have to fix. There are also blue ones that aren't as strict. If it's blue and you strongly disagree with it for some reason you have the option to ignore the warning like this:
1// ignore: rule_name
And you replace
rule_name with whatever rule you want to ignore, so for the
unnecessary_this rule you'd add this:
1// ignore: unnecessary_this
I'd generally advise against this unless you are going to go back and refactor it but are short on time or something. You also have the option to just ignore it and not add anything - your project will still compile with no issues.
I introduced the
lint package in this post but it's not the only option, there's also another one called pedantic that I have used in other projects and can vouch for(it looks like it also uses the same rules that Google use internally). They both have different rule sets but
lint claims that it is 'stricter' on it's pub.dev page - which seems true from my experience using it. Both are great packages and the setup process is basically the same so in the end it's up to what's more comfortable for you.