sumBy method
Sums selector applied to each element.
Avoids the .map(selector).fold(0, (a, b) => a + b) boilerplate that gets
rewritten in every app, and keeps the numeric reduction out of the
element type (you cannot call sum() on Iterable<Order> — only on
Iterable<num>). Returns 0 for an empty iterable, so the result is
always usable without a null check.
Example:
orders.sumBy((o) => o.total); // total across all orders
<Order>[].sumBy((o) => o.total); // 0
Audited: 2026-06-12 11:26 EDT
Implementation
@useResult
num sumBy(num Function(T element) selector) {
num total = 0;
for (final T element in this) {
total += selector(element);
}
return total;
}