Open
Description
I recently blocked on a line similar to:
final myList = const [1,2,3];
I wan't sure about the meaning of const
when initialising a final
variable.
In this situation const
is used to instanciate (create) a new immutable object.
This means that the list object [1, 2, 3]
can't be changed, and the following code won't work:
final myList = const [1, 2, 3];
myList.add(4); // error
If we ignore const
then we are able to use the function add
on the list, and this following code will work:
final myList = [1, 2, 3]
myList.add(4) // myList contains now the value [1, 2, 3, 4]
ref:
- https://dart.dev/guides/language/language-tour#constructors
- https://dart.dev/guides/language/language-tour#using-constructors
- https://stackoverflow.com/questions/21744677/how-does-the-const-constructor-actually-work/21746692#21746692
- https://stackoverflow.com/questions/52581148/when-is-const-optional-in-dart-2