In Dart, if want to create a unmodifiable list, it can use List.unmodifiable() or UnmodifiableListView
List<int> list = [1, 2, 3];
List<int> unmodifiableList = List.unmodifiable(list);
UnmodifiableListView unmodifiableListView = UnmodifiableListView(list);
what different about this?
List.unmodifiable
is a List
constructor; it creates a new List
object. It creates a copy of the original List
, and that copy cannot be mutated. Mutating the original List
will not affect the copy.
UnmodifiableListView
is a wrapper (a "view") around the original List
, and the original cannot be mutated through the UnmodifiableListView
. Mutations to the original List
can still be observed in the UnmodifiableListView
.
For example:
import 'dart:collection';
void main() {
var originalList = [1, 2, 3];
var unmodifiableCopy = List<int>.unmodifiable(originalList);
var unmodifiableView = UnmodifiableListView(originalList);
originalList[0] = -1;
print('$unmodifiableCopy'); // Prints: [1, 2, 3]
print('$unmodifiableView'); // Prints: [-1, 2, 3]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With