In this tutorial you will learn about the Dart Constants and its application with practical example.
Dart Constants refers to an immutable values. Constants are basically literals whose values cannot be modified or changed during the execution of program. Constant must be initialized when declared as values cannot be assigned it to later.
How to Define Constants In Dart
In Dart, constants can be created in following two ways –
- Using final keyword.
- Using const keyword.
In Dart, final and const keyword are used to declare constants. Dart prevents to change the values of a variable declared using the final or const keyword. The final or const keywords can be used in conjunction with data type. A final variable can be set only once while const keyword represents a compile-time constant. The constant declared with const keyword are implicitly final.
Define Constants Using final Keyword
Syntax:-
1 |
final const_name |
Or
1 |
final data_type const_name |
Example:-
1 2 3 4 5 6 |
void main() { final min = 1; final max = 18; print(min); print(max); } |
Output:-
1 2 |
1 18 |
Define Constants Using const Keyword
Syntax:-
1 |
const const_name |
Or
1 |
const data_type const_name |
Example:-
1 2 3 4 |
void main() { const pi = 3.14; print(pi); } |
Output:-
1 |
3.14 |
Note :- Dart throws an exception if an attempt is made to modify variables declared with the final or const keyword.