chunkArray<T> function

List<List> chunkArray<T>(
  1. List<T> array,
  2. int chunkSize
)

Splits an array into chunks of size chunk_size. If the array is not evenly divisible by chunk_size, the first chunk will be smaller than chunk_size.

E.g., arrayChunk(1, 2, 3, 4, 5, 2) => [1, 2, 3, 4, 5] Note: Can be made more efficient by avoiding the reverse() calls.

Implementation

List<List<dynamic>> chunkArray<T>(List<T> array, int chunkSize) {
  final revArray = array.reversed;
  List<List<dynamic>> chunks = List.generate(
    (revArray.length / chunkSize).ceil(),
    (i) =>
        List.from(revArray.skip(i * chunkSize).take(chunkSize).toList().reversed),
  ).toList();
  return chunks.reversed.toList();
}