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;
?
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;
?
By calling
final nums = [];
you created an empty List of dynamic types.
This list by itself is final and you can't reassign it
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.