elementAtOrNull
Returns the element at a given index, or null when the index is out of range.
Lecture
elementAtOrNull walks the iterable and stops as soon as it
reaches index, so it only ever pulls index + 1
elements — cheap even on a huge lazy sequence, and much cheaper than
materializing the whole thing just to index into a List.
elementAtOrNull is the Dart-idiomatic name (it mirrors
Iterable.elementAtOrNull); fxdart also accepts the FxTS
spelling fxNth — they're the same operator. With the top-level function, a negative index
or one past the end simply yields null (the chain method
below is the SDK's and differs for negative indexes); unlike some
languages' array indexing, there's no wraparound-from-the-end behavior
here — the index has to be a valid, non-negative position.
On the sync chain, fx(iterable).elementAtOrNull(index) is the
inherited Iterable method — call it directly on any
Fx chain, since Fx is an
Iterable. Being the SDK method, it returns null
past the end but throws a RangeError for a negative index. For an FxAsyncIterable, use the
top-level elementAtOrNullAsync(index, iterable).
Demo 1 · Basics
Demo 2 · Laziness & async
Fetching index 3 only pulls 4 elements from the million-element range — proven with a peek counter:
Try it yourself
Exercise: use elementAtOrNull to print the silver medalist (index 1), or 'unclaimed'.