How to Split a list into chunks – How do I split or chunk a list into equal parts with Dart?

Hi there, in this quick article we will see how to Split or chunk a list into equal parts with Dart. With Example Code and Quick Explanation

Sometimes We need to add paginate the data for that we need to split the list into Chunks mean Pages for Example:

From This:

var elements = [ 'element1', 'element2', 'element3', 'element4', 'element5', 'element6', 'element7'];

To This:

var newElements = [[ 'element1', 'element2'], ['element3', 'element4'], ['element5', 'element6'],[ 'element7']];

In this example, we are making a List of Lists. That means a List of further Lists which contain some data and the further List Contains the data in 2-2 Chunks each.

And if you can notice element7 is alone in the subList. Because in the main list there is only one element left at the end while making.

Solution:

So the solution is very simple we just need to call on loop for this. First, let me share the code for this and then explain it.

  • Make 2 variables for newList and ChunkSize
  • Start For loop with a length of the main List
  • And increment the Loop with iterable plus ChunkSize
  • Use add function to add new sublists.
  • Inside Add, function use the Sublist function
  • Provide start and the end value to the Sublist Function
  • Full Code Example below
 var newElements = [];
 int ChunkSize= 2;
   for (var i = 0; i < elements.length; i += ChunkSize) {
       newElements.add(elements.sublist(i, i+ChunkSize> elements.length ? elements.length : i + ChunkSize)); 
   }
 print(newElements);

Output:

[[ 'element1', 'element2'], ['element3', 'element4'], ['element5', 'element6'],[ 'element7']]

Here in this code, we take two variables One is for the New List, and the other defines Chunk Size.

Next, we started the loop with the length of our elements list and Increment the var I with i+=ChunkSize (i = i+ChunkSize) in this case we increment by 2 every time.

Next, we are adding the element with add() function inside the loop but by using the sublist() function.

The subList function takes the start and the end value to create the subList. In this case, we are giving i as a Start Value. And for the End Value, we set the condition which is if (i + ChunkSize> element.length) if the page size plus i is greater than the size of the main List then add elements.length else i plus ChunkSize.

Basically, it seems a bit tricky but we are just providing the start value and the end value with the condition for making Sub String.

So here is How do I split or chunk a list into equal parts with Dart? The easiest way to make Chunks

Thank You For Reading

Happy Fluttering


For more Flutter tutorials, Tips, Tricks, Free code, Questions, and Error Solving.

Remember FlutterDecode.com

Leave a Comment