sort
Returns a brand-new sorted list from a comparator — it never mutates its input.
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.