Flutter/Dart analyzing. Part1 — strong-mode
Dart is partially dynamically typed programming language and it is the main cons and pros at the same time
Implicit cast
Let’s imagine that you have the following code:
And you might expect that this code will print something, hehe yeeah, it won’t print anything. The exception will be thrown instead
Just another case with Future
This code will compile and again will throw an exception
And the reasonable question: why it’s even possible to compile this? And the answer is because of Implicit cast. Dart supports implicit upcast and downcast by default, so the compiler believes that you know what you are doing and doesn’t make any additional type checks.
But thanks to the Flutter team, we have an option to turn it on!
Strong Mode
So, the very first step to turn compile-time checks is creating analysis_options.yaml
in the root directory of your project
And add the following
Note: due it is yaml, be careful with blank characters and empty lines
It literally turns implicit-casts off and now in any of the described cases, you will now see.
This is super convenient for people like me who are used to work in a statically typed world.
Implicit dynamic
So, the second scenario
Here we have two functions, the second one returns String, and the first one returns… wait, will it be Future<int> or dynamic? Ok, that was easy and indeed, Dart allows you to do implicit dynamic types, that might be rarely error-prone.
And again we can add extra param to force compiler (analyzer) to check if we have any implicit dynamics.
And here we go
Note: what2 isn’t underlined because the function has an explicit type in the declaration, so it is not a problem.
Summary
The strong mode is a superb tool that helps you to save a lot of time debugging and finding where some implicit cast is broken.
In the second part, we will cover lint for Flutter.
Also considering reading the official documentation about strong-mode https://dart.dev/guides/language/analysis-options
Thanks