What is the difference between var and dynamic and final in dart?| Flutter By Example
This tutorial shows you the usage of var, dynamic and final keywords in the dart, see the between var vs dynamic vs final in the dart.
Difference between var, dynamic, and final in dart?
These three keywords are used to declare the variables in Dart. let’s see the difference between them.
-
var keyword
var
is used to declare and assign multiple values. Following are var keyword features -
variable declared with
var
only change its value -
datatype never be changed.
void main() {
var variable = 123; // declared an int variable with value
print(variable.runtimeType); // int
variable=243; // can change its value
variable = "abc"; // compilation error to change its type, assigned with string
}
- dynamic keyword
The dynamic
keyword is used to assign the dynamic types at runtime.
Following are dynamic
keyword features
- variable declared with
dynamic
change its value - also, datatype can be changed
void main() {
dynamic variable = 123; // declared an int variable with value
print(variable.runtimeType); // int
variable = 243; // can change it's value
variable =
"abc"; // Can change type, assigned with string
print(variable.runtimeType); // String
}
void main() {
final variable = 123; // declared an int variable with value
print(variable.runtimeType); // int
variable = 243; // compilation error, variable never be changed
variable =
"abc"; // compilation error to change its type, assigned with string
}
- final keyword
The final
keyword is used to assign the value only once. Also called compiled time constants.
Following are the final
keyword features
- variable declared with
final
never be changed its value - also, datatype never be changed
var vs dynamic vs final keywords in dart
Let’s see the comparison between var vs dynamic vs final keywords in dart
var | dynamic | final |
---|---|---|
used to declare a variable with assigned multiple values at runtime | used to declare variables to change type and value at runtime | used to declare compile-time constants |
Can change its value | Can change its value | Never be changed its value, once assigned with value |
Datatype can never be changed | Datatype can be changed | datatype can never be changed |