plztrial4me
plztrial4me

Reputation: 303

What's different about 'const' keyword placement in Dart?

void main() {
  var list1 = const [1, 2, 3];
  const list2 = [1, 2, 3];
}

Is there any difference between list1 and list2?

What's different about 'const' keyword placement in Dart?

Upvotes: 14

Views: 2281

Answers (1)

Majid
Majid

Reputation: 2890

The const as keyword makes your object constant where you are not able to reassign any value to it later.

Const means that the object's entire deep state can be determined entirely at compile-time and that the object will be frozen and completely immutable.

In your example

list1 = []; // perfectly fine
list2 = []; // but this throw errors (Error: Can't assign to the const variable 'list2'.)

On the other hand, var allows you to reassign value to the variable.

However, the const after the value makes the value unmodifiable let's take a look at an example

list1.add(22); // ERROR! Cannot add to an unmodifiable list
// but you still can reassign the value 
list1 = [];
// while the 
list2 = []; // throw errors as I said above!

the const for the value in const keyword variable is hidden.

const list2 = const [1,2,3];
list2.add(22); // ERROR! Cannot add to an unmodifiable list

In Short: One makes the memory allocated immutable, the other one the same, and also the pointer pointing to it. in both cases, the list(object) will be immutable.

I hope this helps you understand the difference.

Read more from offical documentation on dart.dev/language-tour#final-and-const

Upvotes: 31

Related Questions