What is the const keyword in Dart?

What is the const  keyword in Dart?

How to use const?

To understand the const keyword lets look at the following code first to see how its declared

void main(){
  const x = [1,2,3];
  print(x);
}
//dart run file.dart =>  [1,2,3]

Now, if we modify the code above to modify const variable x we get:

Error: Can't assign to the const variable 'x'.

void main(){
  const x = [1,2,3];
  x = [4,5,6];
  print(x);
}
//dart run file.dart => Error: Can't assign to const variable 'x'.

Compile time behaviour

What's important to understand is the compile time behaviour here.

  • Compile time constant value is a value which will be a constant while compiling and cannot be modified once declared.

  • If the value of the variable is to be determined at runtime then the compiler will throw a similar error as above.

  • The const list should have constants else it'll error out.

  • Essentially, the value of a const variable is to be known at compile time and once assigned cannot be changed.

So why use const?

For any given const value, a single const object will be created and re-used no matter how many times the const expression(s) are evaluated. They make your software efficient.

How to declare const variables, some examples?

Below are the valid definitions of constants


const a = "blah";

const int b = 2;

const var c = [1,2];

Interestingly,

const c = 5+2; // 5 + 2 is a valid const expression that can be evaluated at compile time

However,

const x = DateTime.now();

//=> Error: Cannot invoke a non-'const' constructor where a const expression is expected.
// Try using a constructor or factory that is 'const'.
// const x = DateTime.now();

So when you declare variable or objects use const as much as possible.

Next, we will look at the final keyword and see when to use the final keyword and when to use const

Did you find this article valuable?

Support Amit Acharya by becoming a sponsor. Any amount is appreciated!