chunked method

Iterable<List<E>> chunked(
  1. int size
)

Divides this Iterable into sub-lists of a given size. The final list might be smaller or equal to the desired size.

The following expression yields [1, 2], [3, 4], and [5]:

[1, 2, 3, 4, 5].chunked(2);

Implementation

Iterable<List<E>> chunked(int size) sync* {
  final iterator = this.iterator;
  while (iterator.moveNext()) {
    final current = <E>[];
    do {
      current.add(iterator.current);
    } while (current.length < size && iterator.moveNext());
    yield current.toList(growable: false);
  }
}