1
void main() {
  final num = [];
  num.add(1);
  print(num);  
}

Output

1

If a final variable is initialized it can't be changed but why does it allow me to change the value whereas it doesn't allow me to reassign the value like num = 5;?

Karan V B
  • 11
  • 2
  • ["final" means single-assignment: a final variable or field must have an initializer. Once assigned a value, a final variable's value cannot be changed. final modifies variables.](https://stackoverflow.com/a/50431087/7666442) – AskNilesh Apr 27 '20 at 14:22
  • 4
    Does this answer your question? [Modifying final fields inside the class in Dart](https://stackoverflow.com/questions/26235849/modifying-final-fields-inside-the-class-in-dart) – AskNilesh Apr 27 '20 at 14:23
  • Because that var is final and you cannot change it to DIFFERENT array - but array itself is mutable and you are allowed to change its internal state (eg adding elements) – Antoniossss Apr 27 '20 at 15:14

1 Answers1

5

By calling

final nums = [];

you created an empty List of dynamic types.

enter image description here

This list by itself is final and you can't reassign it

enter image description here

However, you can easily add new items to the List as this is just a method on the List.

In other words making a variable final means that it cannot be reassigned, but it doesn't mean that it cannot change.

A final variable can be set only once

Please refer to the Dart language tour to learn more.

One important remark is that num is a class in Dart that may be double or integer, so it's not a good practice to use it as variable name.

Dominik Roszkowski
  • 2,715
  • 1
  • 19
  • 46