firstOrNull
Returns the first element of an iterable, or null when it's empty.
Lecture
firstOrNull pulls exactly one element off the front of an
iterable and hands it back — or null if there isn't one.
firstOrNull is the Dart-idiomatic name (it mirrors
Iterable.firstOrNull); fxdart also accepts the FxTS spelling
head — they're the same operator. FxTS's head
returns undefined on an empty array; Dart has no
undefined, so every "might not exist" result in this corner
of the API collapses to null. That means the natural way to
consume it is firstOrNull(list) ?? fallback.
Because firstOrNull only calls moveNext() once,
it costs nothing to call on a huge — even infinite — lazy pipeline:
nothing upstream of it runs beyond the single element it needs.
It comes in data-first form (firstOrNull(iterable)) and an
async form for FxAsyncIterable. On the sync chain,
fx(iterable).firstOrNull is the inherited
Iterable getter — no parens; on the async chain it's a
method, .firstOrNull().
Demo 1 · Basics
Empty in, null out — no exception, no orElse callback required:
Demo 2 · Laziness, and async short-circuiting
Only one element is ever pulled from the million-element range below.
In the async example, the chain awaits the first
delay(...) and never even bothers with the second:
Try it yourself
Exercise: use firstOrNull so this prints the first score, or
0 when the list is empty.