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> fxSortBy<A>(Object? Function(A a) f, Iterable<A> iterable) Future<List<A>> fxSortByAsync<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>>.

sortBy is stable: elements whose keys are equal keep the order they arrived in, whatever the key type. (Before 0.9.1 that held for int and double keys only — String and other keys went through List.sort, which is free to reorder ties.) Stability is what makes a two-level order possible without a comparator: sort by the secondary key, then by the primary one.

For descending order use sortByDesc, which is stable too. For anything beyond chained single keys, drop back down to sort with an explicit comparator.

Demo 1 · Basics

Demo 2 · Async — already a terminal

Demo 3 · Stable — a two-level order

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 · fxPluck — extract the same key without sorting