forEach<T> method

Future forEach <T>(
  1. Iterable<T> elements,
  2. FutureOr action(
    1. T element
    )
)

Performs an action for each element of the iterable, in turn.

The action may be either synchronous or asynchronous.

Calls action with each element in elements in order. If the call to action returns a Future<T>, the iteration waits until the future is completed before continuing with the next element.

Returns a Future that completes with null when all elements have been processed.

Non-Future return values, and completion-values of returned Futures, are discarded.

Any error from action, synchronous or asynchronous, will stop the iteration and be reported in the returned Future.

Implementation

static Future forEach<T>(Iterable<T> elements, FutureOr action(T element)) {
  var iterator = elements.iterator;
  return doWhile(() {
    if (!iterator.moveNext()) return false;
    var result = action(iterator.current);
    if (result is Future) return result.then(_kTrue);
    return true;
  });
}

© 2012 the Dart project authors
Licensed under the Creative Commons Attribution-ShareAlike License v4.0.
https://api.dart.dev/stable/2.13.0/dart-async/Future/forEach.html