Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I split or chunk a list into equal parts, with Dart?

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?

like image 537
Seth Ladd Avatar asked Mar 08 '14 19:03

Seth Ladd


People also ask

How do you slice a list in flutter?

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.

How do you split a string into a list in flutter?

You can use split() method to break String into List Array in Dart or Flutter.

How do you list an object by another list of items in Dart?

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));


3 Answers

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

like image 161
Seth Ladd Avatar answered Oct 08 '22 20:10

Seth Ladd


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']]
like image 32
cbracken Avatar answered Oct 08 '22 22:10

cbracken


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));
}
like image 22
Erik K. Avatar answered Oct 08 '22 20:10

Erik K.