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

groupedBy

Groups as chainable (key, items) records — aggregate per group without leaving the pipeline.

List<({K key, List<A> items})> groupedBy<A, K>(K Function(A a) f, Iterable<A> iterable) Future<List<({K key, List<A> items})>> groupedByAsync<A, K>(FutureOr<K> Function(A a) f, FxAsyncIterable<A> iterable) Fx<({K key, List<T> items})> Fx<T>.groupedBy<K>(K Function(T a) f) // chain (sync) Future<List<({K key, List<T> items})>> FxAsync<T>.groupedBy<K>(FutureOr<K> Function(T a) f) // chain (async)

Lecture

groupBy is a terminal: it hands you a Map, and the moment you want "total per group, sorted, top 3" you are re-entering the pipeline through fx(map.entries) with kv.key / kv.value ceremony. groupedBy is the same grouping as a chainable view: each group is a named record (key: …, items: …), so per-group aggregation, sorting, and taking continue in the very same chain — and downstream code reads g.key / g.items instead of positional $1 / $2.

Groups appear in first-seen key order, exactly like groupBy's map iterates. Like sortBy, it must see every value before it can yield the first group, so the grouping itself is eager while the chain around it stays composable.

This is a Dart-native addition (no FxTS counterpart) — reach for groupBy when you want keyed lookups, and groupedBy when the groups are just an intermediate step of a longer pipeline.

Demo 1 · Group → aggregate → rank, one chain

Demo 2 · Async

Try it yourself

Exercise: top spending category without touching Map.entries.

Related: groupBy — the same grouping as a keyed Map · countBy — when the only aggregate is a count · sortByDesc — the natural next step for rankings