In Dart language, Constants are objects whose values cannot be changed during the execution of the program. Hence, they are a type of immutable object. A constant cannot be reassigned any value if a value has been assigned to it earlier. If we try to reassign any value to a constant, Dart throws an exception.
In Dart language, we can define constants by using 2 keywords :
- final keyword
- const keyword
Creating a constant using the final keyword:
The final keyword is used to hardcode the values of the variable and it cannot be altered in the future.
Syntax:
// Without datatype
final variable_name;
// With datatype
final data_type variable_name;
Example:
Dart
main() {
final var1 = 12;
print(var1);
final String var2 = "GeeksForGeeks" ;
print(var2);
}
|
Output:
12
GeeksForGeeks
Creating a constant using const keyword
The const keyword behaves exactly like the final keyword. The difference between final and const is that the const makes the variable constant from compile-time only.
Syntax:
// Without datatype
final variable_name;
// With datatype
final data_type variable_name;
Example:
Dart
main() {
const var1 = 32;
print(var1);
const String var2 = "GeeksForGeeks but with const" ;
print(var2);
}
|
Output:
32
GeeksForGeeks but with const
Last Updated :
12 Mar, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...