Assume I have a list like:
var letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
I would like a list of lists of 2 elements each:
var chunks = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']];
What's a good way to do this with Dart?
In Dart, we use the List. sublist( ) method to slice a list. This method takes the starting index as the first argument and the ending index as the second argument and returns a List of sliced items. If you don't pass the second argument then List.
You can use split() method to break String into List Array in Dart or Flutter.
List<SomeClass> list = list to search; List<String> matchingList = list of strings that you want to match against; list. where((item) => matchingList. contains(item. relevantProperty));
Here is another way:
var chunks = [];
int chunkSize = 2;
for (var i = 0; i < letters.length; i += chunkSize) {
chunks.add(letters.sublist(i, i+chunkSize > letters.length ? letters.length : i + chunkSize));
}
return chunks;
Run it on dartpad
Quiver (version >= 0.18) supplies partition()
as part of its iterables library (import 'package:quiver/iterables.dart'). The implementation returns lazily-computed Iterable
, making it pretty efficient. Use as:
var letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
var pairs = partition(letters, 2);
The returned pairs
will be an Iterable<List>
that looks like:
[['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']]
A slight improvement on Seth's answer to make it work with any list or chunk size:
var len = letters.length;
var size = 2;
var chunks = [];
for(var i = 0; i< len; i+= size)
{
var end = (i+size<len)?i+size:len;
chunks.add(letters.sublist(i,end));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With