dwyl / learn-dart

🎯Learn the Dart programming language to build cross-platform (Mobile, Web & Desktop) Apps with Flutter!
GNU General Public License v2.0
33 stars 8 forks source link

The `const` constructor #8

Open SimonLab opened 4 years ago

SimonLab commented 4 years ago

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: