Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

constants

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?

  • between 'const' before the list literal and 'const' before the variable name
like image 282
plztrial4me Avatar asked Feb 03 '26 23:02

plztrial4me


1 Answers

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

like image 149
Majid Avatar answered Feb 06 '26 08:02

Majid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!