maxBy
The element whose key is largest — one walk, no sort, null when empty.
Lecture
maxBy answers "which element has the biggest
key?" — not "what is the biggest number?" (that's
max). It walks the pipeline
once, keeping the current best element, so it is O(n)
where the tempting sortBy(key).head() shape pays
O(n log n) and materializes a sorted list it never needs.
Keys are compared exactly like
sortBy compares them
(Comparable.compare), and on ties the first
element encountered wins — so maxBy over a date-sorted list
gives you the earliest of the equally-largest.
Empty input returns null, like
head and
last — Dart's nullable types replace
FxTS's undefined here. This is a Dart-native addition
(FxTS only ships the numeric max); the name follows
Kotlin's maxByOrNull shape.
Demo 1 · Basics, empty case & ties
Demo 2 · Async
Try it yourself
Exercise: find the biggest expense without sorting.