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
CodePudding user response:
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
I hope this helps you understand the difference.