What is the const keyword in Dart?
const Keyword
A variable declared with the const keyword cannot have any other value given to it. The variable is also known as a compile-time constant. It means that its value must be declared while the program is being compiled. A const variable can not be reassigned once declared in a program.
When we use const on an object, the object’s whole deep state is rigidly fixed at compilation time, and the object is deemed frozen and entirely immutable.
Syntax
// Without datatype
const variable_name;
// With datatype
const data_type variable_name;
Code
The following code shows how to implement the const keyword in Dart:
void main() {// Declaring and assigning variable without datatype// using const keywordconst x = 5;// display valueprint(x);// Declaring and assigning variable with datatype// using const keywordconst int y = 10;// display valueprint(y);}
Explanation
- Line 6: We declare and assign variable
xwithout datatype usingconstkeyword.
- Line 9: We display the value of variable
xvalue.
- Line 13: We declare and assign variable
ywithout datatype using theconstkeyword.
Note: The compiler will throw an error if we try to reassign the values in the above code.
Code
The following code shows the error, thrown when reassigning a const variable:
void main(){// declaring variableconst num = 25;print(num);// Reassigning the valuenum = 10;print(num);}
Explanation
- Line 3: We declare and assign variable
numwithout datatype usingconstkeyword. - Line 4: We display the value of the variable
num. - Line 7: We reassign the variable
num. - Line 8: We display the value of the variable
num.