Book Image

Mastering Dart

By : Sergey Akopkokhyants
Book Image

Mastering Dart

By: Sergey Akopkokhyants

Overview of this book

Table of Contents (19 chapters)
Mastering Dart
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Unmodifiable collections


The collection framework has unmodifiable versions of the existing collections with the following advantages:

  • To make a collection immutable once it has been built and not modify the original collection to guarantee absolute immutability, although the elements in that collection are still mutable

  • To allow read-only access to your data structure from the client code and the client code can look into it without modifying it while you have full access to the original collection

The unmodifiable list

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...