Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Dart, what different about List.unmodifiable() and UnmodifiableListView?

Tags:

dart

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?

like image 878
songjhh Avatar asked Apr 24 '20 08:04

songjhh


1 Answers

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]
}
like image 154
jamesdlin Avatar answered Nov 13 '22 08:11

jamesdlin