chunked method
Returns a new lazy Iterable where elements are grouped into chunks of a
specified size.
This method splits the current iterable into chunks, each containing up to
size elements. The resulting iterable consists of lists, where each list
represents a chunk of elements from the original iterable. If the last chunk
contains fewer than size elements, it will be included as is.
-
Parameters:
size: The maximum number of elements in each chunk. It should be greater than or equal to 1.
-
Returns: A new lazy Iterable where elements are grouped into chunks of the specified
size. -
Throws:
- ArgumentError: If the requested
sizeis less than 1.
- ArgumentError: If the requested
-
Examples:
Iterable<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]; Iterable<List<int>> chunks = numbers.chunked(3); print(chunks); // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Note: This method does not modify the original iterable. It creates a new lazy iterable with chunks of elements from the original iterable.
Implementation
Iterable<List<T>> chunked(int size) sync* {
if (size < 1) {
throw ArgumentError('Requested chunk size $size is less than one.');
}
var currentChunk = <T>[];
for (var current in this) {
currentChunk.add(current);
if (currentChunk.length >= size) {
yield currentChunk;
currentChunk = <T>[];
}
}
if (currentChunk.isNotEmpty) {
yield currentChunk;
}
}