To split a list in Dart, you can use the sublist
method or iterate through the list manually to create sublists.
In this example,
numbers
with initial integer values.sublist
method to create a sublist from the original list, specifying the start and end indices.sublist
method returns a new list containing the specified range of elements from the original list.void main() {
List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8];
int chunkSize = 3;
for (int i = 0; i < numbers.length; i += chunkSize) {
List<int> chunk = numbers.sublist(i, i + chunkSize < numbers.length ? i + chunkSize : numbers.length);
print('Chunk: $chunk');
}
}
Chunk: [1, 2, 3] Chunk: [4, 5, 6] Chunk: [7, 8]
In this example,
numbers
with initial integer values.void main() {
List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8];
int chunkSize = 3;
List<List<int>> chunks = [];
for (int i = 0; i < numbers.length; i += chunkSize) {
chunks.add(numbers.sublist(i, i + chunkSize < numbers.length ? i + chunkSize : numbers.length));
}
for (List<int> chunk in chunks) {
print('Chunk: $chunk');
}
}
Chunk: [1, 2, 3] Chunk: [4, 5, 6] Chunk: [7, 8]
In this tutorial, we learned How to Split a List in Dart language with well detailed examples.