chunked method

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

Splits this collection into a new lazy Iterable of lists each not exceeding the given size.

The last list in the resulting list may have less elements than the given size.

size must be positive and can be greater than the number of elements in this collection.

Implementation

Iterable<List<E>> chunked(int size) sync* {
  if (size < 1) {
    throw ArgumentError('Requested chunk size $size is less than one.');
  }

  var currentChunk = <E>[];
  for (var current in this) {
    currentChunk.add(current);
    if (currentChunk.length >= size) {
      yield currentChunk;
      currentChunk = <E>[];
    }
  }
  if (currentChunk.isNotEmpty) {
    yield currentChunk;
  }
}