What is the point of specifying variables at all in dart instead of just using var and dynamic?
I am new to dart and would like to know for future projects.
What is the point of specifying variables at all in dart instead of just using var and dynamic?
I am new to dart and would like to know for future projects.
There are several reasons why one would do such a thing.
Sometimes, you want a variable to be of a more permissive type than inference gives you.
For example, the following snippet won't compile as-is, because score
is an int
:
var score = 0;
score += 0.5;
Instead, score
must be explicitly defined as a num
value:
num score = 0;
score += 0.5;
This also applies for nullable values.
// var score = 0; // Won't compile
int? score = 0; // This works
score = null;
Conversely, sometimes type inference is not specific enough.
Consider the following example:
const myList = [];
What types can myList
hold? In this case, the literal []
creates an empty list of type dynamic
. This can be restricted in two separate ways.
const myList = <int>[]; // LHS type inference
const List<int> myList = []; // RHS type inference
It's often beneficial to use type annotations on public API elements, as detailed in the Effective Dart: Design guidelines and type_annotate_public_apis
linter rule.