design-patterns

Quick-reference guide to software design patterns with concise Dart examples.

View project on GitHub

Provides a way to access elements of a collection sequentially without exposing its underlying structure.

Dart has this built-in with Iterable and Iterator.

class NumberRange implements Iterable<int> {
  final int start, end;
  NumberRange(this.start, this.end);

  @override
  Iterator<int> get iterator => _RangeIterator(start, end);
}

class _RangeIterator implements Iterator<int> {
  final int _end;
  int _current;

  _RangeIterator(int start, this._end) : _current = start - 1;

  @override
  int get current => _current;

  @override
  bool moveNext() {
    _current++;
    return _current <= _end;
  }
}

// Usage
for (final n in NumberRange(1, 5)) {
  print(n); // 1, 2, 3, 4, 5
}