Amit Acharya
Runtime Terror Blogs ( •̀ᴗ•́ )و ̑̑


Runtime Terror Blogs ( •̀ᴗ•́ )و ̑̑


What is the const keyword in Dart?

Amit Acharya's photo
Amit Acharya
·Jul 8, 2022·

2 min read

What is the const  keyword in Dart?

Table of contents

  • How to use const?
  • Compile time behaviour
  • So why use const?
  • How to declare const variables, some examples?

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];
//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];
//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];


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


const x =;

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

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!

See recent sponsors Learn more about Hashnode Sponsors
Share this