Esta página ainda não foi traduzida, por isso é exibida em inglês. Ajude a traduzir

sortBy

Sorts ascending by a key you extract, instead of writing a comparator by hand.

List<A> sortBy<A>(Object? Function(A a) f, Iterable<A> iterable) Future<List<A>> sortByAsync<A>(Object? Function(A a) f, FxAsyncIterable<A> iterable) Fx<T> Fx.sortBy(Object? Function(T a) f) // chain (sync) — still lazy, call .toList() Future<List<T>> FxAsync.sortBy(Object? Function(T a) f) // chain (async) — already a terminal

Lecture

sortBy is sort's convenience sibling: instead of writing (a, b) => a.age.compareTo(b.age) yourself, you give sortBy a key extractor — (a) => a['age'] — and it sorts by the extracted keys, always ascending, always comparing them with Comparable.compare.

It is not sort((a, b) => compare(f(a), f(b))) underneath, and the difference is visible in your callback: that form would call f twice per comparison — about 2·n·log n times. sortBy extracts each key exactly once, then sorts by the extracted keys, so an expensive key extractor costs n calls, not 2·n·log n. Keep f pure and cheap all the same: the number of calls is guaranteed, the order they happen in is not.

Every guarantee from sort carries over unchanged: the result is always a new list, never a mutation of the input. And the same chain-form nuance applies too — on the sync Fx chain, .sortBy(f) returns another Fx<T>, so you still need .toList() to materialize it, while on the FxAsync chain, .sortBy(f) is already a terminal returning Future<List<T>>.

If you need descending order, or a multi-key sort, drop back down to sort with an explicit comparator — sortBy only covers the common "ascending by one extracted key" case.

Demo 1 · Basics

Demo 2 · Async — already a terminal

Try it yourself

Exercise: sort the people by age, youngest first.

Related: sort — the comparator-based form this builds on · min · max — for a single extreme instead of a full ranking · pluck — extract the same key without sorting