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 keyword
const x = 5;
// display value
print(x);
// Declaring and assigning variable with datatype
// using const keyword
const int y = 10;
// display value
print(y);
}

Explanation

  • Line 6: We declare and assign variable x without datatype using const keyword.
  • Line 9: We display the value of variable x value.
  • Line 13: We declare and assign variable 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.

Code

The following code shows the error, thrown when reassigning a const variable:

void main(){
// declaring variable
const num = 25;
print(num);
// Reassigning the value
num = 10;
print(num);
}

Explanation

  • Line 3: We declare and assign variable num without datatype using const keyword.
  • 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.