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

BidirectionalIterator


Sometimes, we need to iterate over a collection of elements in both directions. To help in such cases, Dart provides BidirectionalIterator. In the following code, BiListIterator is the implementation of BidirectionalIterator:

class BiListIterator<E> implements BidirectionalIterator<E> {
  final Iterable<E> _iterable;
  final int _length;
  int _index;
  E _current;

The constructor has an extra optional back parameter that defines the direction of the iteration:

  BiListIterator(Iterable<E> iterable, {bool back:false}) :
    _iterable = iterable, _length = iterable.length,
    _index = back ? iterable.length - 1 : 0;

  E get current => _current;

The following code shows the moveNext method of the Iterator to move forward. This and the next method compare the length of the Iterable and the actual length of the collection to check concurrent modifications. The code is as follows:

  bool moveNext() {
    int length = _iterable.length;
    if (_length...