Эта страница ещё не переведена, поэтому показана на английском. Помогите с переводом

sort

Returns a brand-new sorted list from a comparator — it never mutates its input.

List<A> sort<A>(int Function(A a, A b) f, Iterable<A> iterable) List<A> toSorted<A>(int Function(A a, A b) f, Iterable<A> iterable) // alias of sort Future<List<A>> sortAsync<A>(int Function(A a, A b) f, FxAsyncIterable<A> iterable) Fx<T> Fx.sort(int Function(T a, T b) f) // chain (sync) — still lazy, call .toList() Future<List<T>> FxAsync.sort(int Function(T a, T b) f) // chain (async) — already a terminal

Lecture

sort takes a standard Dart comparator — return negative if a should come before b, positive if after, zero if tied — and produces a sorted result. The important difference from JavaScript's (and FxTS's) Array.prototype.sort is that FxDart's sort never mutates its input. It always allocates a new List (List.of(iterable)..sort(f)), leaving the original iterable exactly as it was. FxTS later added toSorted as the non-mutating alternative to its mutating sort; in FxDart, toSorted is simply an alias — since sort was already non-mutating, there was nothing left to differentiate.

There's a nuance on the chain form worth calling out explicitly: on the sync Fx chain, .sort(f) returns another Fx<T> — not a List<T> — because Fx wraps its underlying sorted list to stay chainable. You still need a terminal like .toList() to get a concrete List out of it. The async chain doesn't have that wrinkle: FxAsync.sort(f) is already a terminal that returns Future<List<T>> directly, because FxAsync can't return itself from something that needs to await the whole pipeline first.

Reach for sortBy instead when you just want to sort by a key you extract, rather than writing the comparator yourself.

Demo 1 · Basics, no mutation, and toSorted

Demo 2 · Async — already a terminal

Try it yourself

Exercise: sort the numbers in descending order.

Related: sortBy — sort by an extracted key instead of a comparator · reverse — flip element order without comparing · partition — split into two lists by a predicate