How to loop through two lists at the same time - Flutter

Viewed 549

I'm trying to loop through two lists at the same time

For example

List A = ['Chapter 1','Chapter 2','Chapter 3'];
List B = ['Paragraph 1','Paragraph 2','Paragraph 3'];

for(var chapter in A)  // This would itreate through only first list (A), How can I iterate through both list
children: [
     Text(chapter);   
     Text(paragraph);
]

I need to iterate through both lists at the same time in "for" loop.

3 Answers

Here is the code:

  List A = ['Chapter 1','Chapter 2','Chapter 3'];
  List B = ['Paragraph 1','Paragraph 2','Paragraph 3'];
  for (int i = 0; i < A.length; i++) {
      print ("${A[i]}");
      print ("${B[i]}");
  }

Let me know if this does not help.

final c = zip([a, b]).map((item) => Foo(item[0], item[1])).toList();

I went along with Randal Schwartz's note about IterableZip. Note that I was not able to find any zip mentioned by Gbenga, and also note that package:collection/iterable_zip.dart is deprecated, you'd need to import simply the collection.dart, like so:

import 'package:collection/collection.dart';

final A = ['Chapter 1','Chapter 2','Chapter 3'];
final B = ['Paragraph 1','Paragraph 2','Paragraph 3'];
for (final pairs in IterableZip([A, B])) {
    print(pairs[0]);
    print(pairs[1]);
}

Some more notes:

  • final A and final B variables will be typed List<String> lists, I disadvise dynamic List A.
  • I have not specified template type for IterableZip, but in some cases (in a complex case where I used it) you may need to explicitly type it like IterableZip<String>, so in the loop you can more conveniently access the members. In this simple case the compiler/interpreter can infer the type easily.
  • Some other answers in other StackOverflow issues mention quiver, but unless you need it for some other features you don't have to add another extra package dependency to your project. The standard collection package has this IterableZip
Related