Nothing soothes more than clean code!
Don’t you get clumsy looking at dirty, messed up code? One should always follow strict rules to make code clean! Let’s see how you can do that with lint rules in Dart!
One should always follow the practice to write clean, refactored and well-documented code! It’s not just for the benefit of you, but it also helps others who check your code.
Dart has some of the in-built lint rules which allow developers to write proper clean code. Projects created with flutter create
using Flutter version 2.3.0-12.0.pre or newer are already enabled to use the latest set of recommended lints. Projects created prior to that version can upgrade to it with the instructions in this guide. However, you can always make the rules stricter by specifying your custom lint rules!
There are many packages available for lint rules:
And many more…
Let’s see how we can use flutter_lints in our app to write better code!
Step 1: Add flutter_lints into dev_dependency and run flutter pub get!
dev_dependencies:
flutter_lints: ^1.0.4
Step 2: Create analysis_options.yaml file in the root of your project
You need to create analysis_options.yaml
file at the root of the package (alongside the pubspec.yaml
file) and include: package:flutter_lints/flutter.yaml
from it. This file is used when the Dart Analyzer analyses your code. You can include different rules in this and specify the severity of the rules too. Example of analysis_options.yaml
file:
Here, under linter, we have specified rules. When we specify rules, the default dart style rules also gets included (Eg: Prefer const with constant constructors, etc.). We can specify some custom rules also which we want in our project. If you want to turn any rule on or off, you can specify directly like avoid_print: false
, by default, it will be true.
Under analyzer, we have specified errors. Here, we can specify the severity of particular rules. Let’s say, I don’t want that anyone uses print statements in my code. They can use the dart logger but not print. Whenever they write a print statement, the analyzer should show an error, so we can specify avoid_print: error
, if want to be just a warning you can specify it as a warning.
You can check custom lint rules at https://dart-lang.github.io/linter/lints and add them to your project to make it more strict. Remember, stricter the rules, cleaner the code!
Check out the example code on GitHub!
Hope you enjoyed this article!
If you loved it, you can Buy Me A Coffee!
Don’t stop, until you are breathing!💙
- Abhishek Doshi