Enforce stricter types in Flutter
I just started to migrate my Simple Animations package to an updated rule set of pendantic. I thought this is a good occasion to write something about that “hidden gem”.
What is pendatic? It sounds funny but it’s dart own linting mechanism. A linter as tool for static analysis of your Flutter code. It contains rules that helps you write good code and find errors at compile time.
Example: Strings
Personally I am used to write strings in double quotes because I have Java background. But over time the trend has changed to single quotes. The current best praticise in Flutter is to use single quotes for strings.
As the result my code would look unfimilar to other Flutter developers.
Pendatic comes to help
Pendatic is the official ruleset of the dart developers. The dart compiler analyses my code and shows an issue everywhere I used double quotes strings.
Correct string formatting is very basic issue. As a framework developer there are more crucial issues like being not type safe.
Whenever I forget to specify an exact type, dart makes it dynamic. For example:
doStuff() {
doOtherStuff();
}
It’s a simple function with no return values. But dart assumed it’s return type as dynamic since the void keyword is missing.
The correct code should look like this:
void doStuff() {
doOtherStuff();
}
Configuring pedantic
Adding pedantic to your project and enforcing stricter types are two simple steps.
Add pedantic dependency as a dev_dependencies
dev_dependencies:
flutter_test:
sdk: flutter
pedantic: ^1.9.0
Create a analysis_options.yaml
in your Fluttter project root directory:
include: package:pedantic/analysis_options.1.9.0.yamlanalyzer:
exclude: [build/**]
strong-mode:
implicit-casts: false
implicit-dynamic: false
The first line includes a default rule set. I configured my file to additionally hint me, whenever I use implicit casts and implicit dynamics.
Now dart helps me to write better and more typesafe code.
You can configure the linting rules to match your needs. The less you move away from a default rule set, the better!
There is a dart guide that covers that topic.
In Android Studio there is also a “Dart Analysis” tab that lists all issues in your project.
Leave some claps if you found this article useful :-)
Until next time
— Felix —