THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
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.
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 it's value
variable = "abc"; // compilation error to change its type, assigned with string
}
dynamic
keyword is used to assign the dynamic types at runtime.
Following are dynamic
keyword features
dynamic
change its valuevoid 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
}
The final
keyword is used to assign the value only once. Also called compiled time constants.
Following are final
keyword features
final
never be changed its valueLet’s see the comparison between var vs dynamic vs final keywords in dart
var | dynamic | final |
---|---|---|
used to declare a variable with assign 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 |
🧮 Tags
Recent posts
How to Convert String to Int in swift with example How to Split a String by separator into An array ub swift with example How to disable unused code warnings in Rust example Golang Tutorials - Beginner guide Slice Examples Golang Array tutorials with examplesRelated posts