dart: Mutability of lists
By default, dart lists are mutable and it might lead to code that is hard to debug and predict.
void main() {
var a = [0,1, 2,3] ;
var b = a;
b.add(4);
print(a);
}
// prints [0, 1, 2, 3, 4]
A change (calling add method) on b causes a ripple effect on the variable a.
There are different ways to prevent this. One way is to use the spread operator.
void main() {
var a = [0,1, 2,3] ;
var b = [...a];
b.add(4);
print(a);
}
// prints [0, 1, 2, 3]
To prevent any mutation on variable a, we can make it unmodifiable.
import 'dart:collection';
void main() {
var a = UnmodifiableListView([0,1, 2,3]);
var b = [...a];
b.add(4);
// a.add(5); Unsupported operation: Cannot add to an unmodifiable list
print(a);
}
If we try to change the list a, we will get error.