The collection framework has unmodifiable versions of the existing collections with the following advantages:
The unmodifiable collection based on the List
class is UnmodifiableListView
. It creates an unmodifiable list backed by the source provided via the argument of the constructor:
import 'dart:collection'; void main() { var list = new List.from([1, 2, 3, 4]); list.add(5); var unmodifiable = new UnmodifiableListView(list); unmodifiable.add(6); }
The execution fails when we try adding a new element to an unmodifiable collection, as shown in the following code:
Unsupported operation: Cannot add to an unmodifiable list #0 ListBase&&UnmodifiableListMixin.add (…) #1 main (file:///…/bin/unmodifiable.dart:7:19) …
The following diagram shows the class hierarchy of UnmodifiableListView
:
Another unmodifiable collection is UnmodifiableMapView
, which is based on the Map
class. It disallows modifying the original map via the view wrapper:
import 'dart:collection'; void main() { var map = new Map.fromIterables( [1, 2, 3, 4], ['1', '2', '3', '4']); map[5] = '5'; var unmodifiable = new UnmodifiableMapView(map); unmodifiable[6] = '6'; }
Any attempt to modify the collection throws a runtime exception as follows:
Unsupported operation: Cannot modify unmodifiable map #0 MapView&&_UnmodifiableMapMixin.[]= (…) #1 main (file:///…/bin/unmodifiable_map.dart:7:15) …
The following diagram shows the class hierarchy of UnmodifiableMapView
:
13.58.116.51