本页尚未翻译,因此以英文显示。 参与翻译

forEach

Runs a function once per element, purely for its side effects.

void forEach<A>(void Function(A a) f, Iterable<A> iterable) Future<void> forEachAsync<A>(FutureOr<void> Function(A a) f, FxAsyncIterable<A> iterable) void Fx.forEach(void Function(T a) f) // chain (inherited from Iterable) Future<void> FxAsync.forEach(FutureOr<void> Function(T a) f) // chain void each<A>(void Function(A a) f, Iterable<A> iterable) // FxTS alias

Lecture

forEach is the Dart-idiomatic name; fxdart also accepts the FxTS spelling each — they're the same operator. It's a terminal operator, like toList — calling it pulls every value through the whole chain. The difference is what it does with those values: instead of collecting them into a List, it just runs f for each one and returns void. Use it when you're printing, logging, writing to a database, or otherwise producing an effect, and you don't need the values back.

On a sync chain, .forEach(f) is Dart's own Iterable.forEach, inherited by Fx; the async chain and the data-first forEach(f, iterable) form are supplied by fxdart so the operator reads the same everywhere.

forEachAsync (or .forEach() on an FxAsync chain) awaits f for every element, strictly in the order the elements arrive — even if some individual calls would finish faster than others, forEach always processes one at a time in sequence. If you want overlap, add .concurrent(n) upstream before .forEach().

Demo 1 · Basics

Demo 2 · Async, strictly in order

Even though each element sleeps for a different length of time, forEachAsync still processes them 1, 2, 3 — never out of order:

Try it yourself

Exercise: use forEach to print a receipt line for every order and keep a running total.

Related: toList — terminal op that collects a List instead · consume — terminal op that discards results and can stop early · peek — same idea, but lazy (not terminal) · fx — the chain that forEach terminates