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

sortByDesc

Sort by any comparable key, descending — the negation trick, retired.

List<A> sortByDesc<A>(Object? Function(A a) f, Iterable<A> iterable) Future<List<A>> sortByDescAsync<A>(Object? Function(A a) f, FxAsyncIterable<A> iterable) Fx<T> Fx<T>.sortByDesc(Object? Function(T a) f) // chain (sync) Future<List<T>> FxAsync<T>.sortByDesc(Object? Function(T a) f) // chain (async)

Lecture

Rankings want their biggest value first, and until now the only one-liner was sortBy((a) => -key) — a trick that works only for numbers. Dates, strings, and every other Comparable have no minus sign. sortByDesc is sortBy with the comparison swapped: same key extraction (each key computed exactly once), same unboxed fast paths for double/int/String keys, same never-mutates-the-input contract.

The classic shape it replaces is the "top N" ranking: sortByDesc(key).take(n) reads as written, where the ascending spelling needed the negation and a comment explaining it. For "newest first" over dates it is the only direct spelling at all.

Dart-native addition — the name follows Kotlin's sortedByDescending. When you need the single largest element rather than the full ordering, skip the sort entirely: maxBy is O(n).

Demo 1 · Rankings without negation

Demo 2 · Keys numbers can't fake

Try it yourself

Exercise: newest-first without negating anything.

Related: sortBy — ascending twin · maxBy — one walk when only the top element matters · take — the second half of every "top N"