Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I iterate through two lists in parallel in Dart?

Tags:

dart

I have two lists that I have confirmed are the same length. I want to operate on them at the same time. My code currently looks something like this:

var a = [1, 2, 3];
var b = [4, 5, 6];
var c = [];
for(int i = 0; i < a.length; i++) {
  c.add(new Foo(a, b));
}

It seems a bit clunky to count up to the length of list A in this fashion. Is there a nicer and more Dart-y way of accomplishing this task?

like image 643
jxmorris12 Avatar asked Jul 20 '17 19:07

jxmorris12


People also ask

How do you combine two lists in darts?

Using addAll() method to add all the elements of another list to the existing list. Creating a new list by adding two or more lists using addAll() method of the list. Creating a new list by adding two or more list using expand() method of the list. Using + operator to combine list.

How do you loop through a list in darts?

forEach() function can be used to loop through a list. You can pass a callback function to it and inside it, we can access the items of the list in each iteration.

How do I iterate through a list in flutter?

How do I iterate through a list in Flutter? forEach() function. The List. forEach() function can be used to loop through a list.


2 Answers

Take a look at the quiver package's zip function.

You could write this as:

var a = [1, 2, 3];
var b = [4, 5, 6];
var c = [];
for (var pair in zip([a, b])) {
  c.add(new Foo(pair[0], pair[1]));
}
like image 122
Harry Terkelsen Avatar answered Oct 09 '22 00:10

Harry Terkelsen


Now that we have list comprehensions in dart:

final c = [for(int i = 0; i<a.length; i+= 1) Foo(a[i], b[i])];
like image 44
Chris Buck Avatar answered Oct 08 '22 22:10

Chris Buck