const
KeywordA 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.
// Without datatype
const variable_name;
// With datatype
const data_type variable_name;
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);}
x
without datatype using const
keyword.x
value.y
without datatype using the const
keyword.Note: The compiler will throw an error if we try to reassign the values in the above 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);}
num
without datatype using const
keyword.num
. num
.num.