Type Inference
Dart compiler is smart enough to infer data types.
Using var for type inference
We don’t need to define the data types explicitly, like int score = 32, or String name = 'Alex'.
Dart can infer the data type automatically using var.
void main() {
var score = 32;
var name = 'Alex';
print('$score -> Runtime type is ${score.runtimeType}');
print('$name -> Runtime type is ${name.runtimeType}');
}
32 -> Runtime type is int Alex -> Runtime type is String
When the data type of the variable is obvious from the value on the right side, then it is perfectly fine to use var.
When the data type isn’t obvious, then we have to specify the data type by explicitly writing it down.
The power of dynamic data type
We have been seeing one thing, and that is we are constantly initializing a variable when we are declaring a var variable.
What will happen if we declare a var without an initial value?
In that case, Dart fails to infer the data type. But it stores the variable as a dynamic variable.
The point of the dynamic variable is to accept any value in future and based on that the inference will take place.
void main() {
var flexibleVar;
flexibleVar = 'Rudolf';
print('The runtime type of the flexibleVar variable is ${flexibleVar.runtimeType}');
flexibleVar = 2.5980;
print('The runtime type of the flexibleVar variable is ${flexibleVar.runtimeType}');
}
The runtime type of the flexibleVar variable is String The runtime type of the flexibleVar variable is double
Notice how flexible is our flexibleVar is when it comes to type inference.
With dynamic, the compiler is unable to catch mistakes related to the data type of that particular variable.
For example, if we try to pass a variable to a function which expects a string, then in the future let’s say we pass an int value to that variable using the dynamic type inference, then the function will throw an error.
But it will not throw an error when the function was running. Once we assign a very different value to that variable that is unexpected for a defined function, then it will throw an error.
The error is there but we don’t know it yet until we pass an unexpected value as an argument to the function.
Dart’s type system was built in order to prevent errors like this. So, it is advised to initialize the var declarations.
With flexibility like that, who would have thought not to use dynamic often!
If we still want to have a variable that changes its types, then we can declare it explicitly as
dynamic flexibleVar;