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 for variable declaration in Dart. Let’s explore their differences.
- var keyword The
var
keyword is utilized to declare variables and assign multiple values. Here are its key features:- Variables declared with
var
can only change their value. - The datatype of a variable declared with
var
cannot be changed.
- Variables declared with
void main() {
var variable = 123; // declared an int variable with a value
print(variable.runtimeType); // int
variable = 243; // can change its value
variable = "abc"; // compilation error when attempting to change its type
}
- dynamic keyword
The dynamic
keyword allows assigning dynamic types at runtime.
Variables declared with dynamic can change both their value and datatype.
Here’s what you need to know about it:
- variable declared with
dynamic
change its value - also, datatype can be changed
void main() {
dynamic variable = 123; // declared an int variable with a value
print(variable.runtimeType); // int
variable = 243; // can change its value
variable = "abc"; // can change its type, assigned with a string
print(variable.runtimeType); // String
}
- final keyword
The final
keyword restricts variable assignment to only once, making it akin to compile-time constants. Its features include
- Variables declared with final cannot change their value after assignment.
- The datatype of a final variable remains constant.
void main() {
final variable = 123; // declared an int variable with a value
print(variable.runtimeType); // int
variable = 243; // compilation error, variable cannot be changed
variable = "abc"; // compilation error when attempting to change its type
}
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 values at runtime | Used to declare variables that can change type and value | Used to declare compile-time constants |
Can change its value | Can change both its value and datatype | Cannot be changed once assigned a value |
Datatype remains constant and cannot be changed | Datatype can be changed | Datatype remains constant and cannot be changed |