chunked method

Iterable<List<T>> chunked(
  1. int size, {
  2. T fill()?,
})

Splits the elements into lists of the specified size.

You can specify an optional fill function that produces values that fill up the last chunk to match the chunk size.

Example:

[1, 2, 3, 4, 5, 6].chunked(2);        // [[1, 2], [3, 4], [5, 6]]
[1, 2, 3].chunked(2);                 // [[1, 2], [3]]
[1, 2, 3].chunked(2, fill: () => 99); // [[1, 2], [3, 99]]

Implementation

Iterable<List<T>> chunked(int size, {T Function()? fill}) {
  ArgumentError.checkNotNull(size, 'chunkSize');
  if (size <= 0) {
    throw ArgumentError('chunkSize must be positive integer greater than 0.');
  }
  if (isEmpty) return const Iterable.empty();
  final countOfChunks = (length / size.toDouble()).ceil();
  return Iterable.generate(countOfChunks, (int index) {
    final chunk = skip(index * size).take(size).toList();

    if (fill != null) {
      while (chunk.length < size) {
        chunk.add(fill());
      }
    }
    return chunk;
  });
}