chunked<T> function

Iterable<Iterable<T>> chunked<T>(
  1. Iterable<T> source,
  2. int chunkSize
)

Splits the source into chunks of a maximum size specified by chunkSize.

Each chunk is yielded as a separate Iterable. If the number of elements is not perfectly divisible by chunkSize, the last chunk will contain the remaining elements.

Example:

final numbers = [1, 2, 3, 4, 5];
final chunks = numbers.chunked(2).toList();
print(chunks); // [[1, 2], [3, 4], [5]]

Implementation

Iterable<Iterable<T>> chunked<T>(
  Iterable<T> source,
  int chunkSize,
) sync* {
  var batch = <T>[];
  for (final item in source) {
    batch.add(item);
    if (batch.length == chunkSize) {
      yield batch;
      batch = <T>[];
    }
  }
  if (batch.isNotEmpty) {
    yield batch;
  }
}