sumBy

Sum a key of every element — map + sum in one step, 0 when empty.

num sumBy<A>(num Function(A a) f, Iterable<A> iterable) Future<num> sumByAsync<A>(FutureOr<num> Function(A a) f, FxAsyncIterable<A> iterable) num Fx<T>.sumBy(num Function(T a) f) // chain (sync) Future<num> FxAsync<T>.sumBy(FutureOr<num> Function(T a) f) // chain (async)

Lecture

sumBy collapses the most common two-stage tail in data pipelines — .map((x) => x.field).sum() — into a single terminal. It folds a running total while extracting the key, so nothing intermediate is materialized and the intent ("total this field") is one call instead of a projection plus an aggregation.

The contract is sum's: an empty pipeline totals to 0, and int keys keep int arithmetic while any double key promotes the total to double.

This is a Dart-native addition (FxTS ships only the numeric sum), in the same family as maxBy / minBy — Kotlin spells it sumOf.

Demo 1 · Basics & the empty case

Demo 2 · Async keys

Try it yourself

Exercise: total the long words' lengths with one call.

Related: sum — when the pipeline already holds numbers · maxBy · minBy — the same by-key family · fold — the general shape this specializes