Iterating two lists at the same time in Dart
It'd be nice to be able to run this kind of loop iterable.map((e) => ...)
on two iterables at the same time.
I really like the iterable.map
syntax because most times, I only care about the actual element values, not the indices. What if I have two iterables of equal length, and I want to iterate over them? The callback of map
only receives the element, not the index, so we can't do something like in Javascript:
// NOT VALID
list1.map((e1, i) {
final e2 = list2[i];
// work with e1 and e2...
});
So what I'd usually do is revert back to indices:
for (var i = 0; i < list1.length; i++) {
final e1 = list1[i];
final e2 = list2[i];
// work with e1 and e2...
}
It works but it sucks because it requires both Iterables to be Lists, and I have to use a var i and mess with indices.
It turns out, there is a built-in feature in dart:collections called IterableZip
that does exactly what I want. See this unit test. The funny thing is, I was simply not able to find it in the docs at all. Googling site:api.dart.dev iterablezip
returned nothing.
So here's the cleanest way to iterate over multiple Iterables. First add collection
as a dependency, then use:
import 'package:collection/collection.dart';
IterableZip([iterable1, iterable2,...]).map((els) => ...);
It has all the benefits and none of the drawbacks: it works on Iterables, not Lists, supports any number of iterables, and it does not force indices.