このページはまだ翻訳されていないため、英語で表示されます。 翻訳に参加する

elementAtOrNull

Returns the element at a given index, or null when the index is out of range.

A? elementAtOrNull<A>(int index, Iterable<A> iterable) Future<A?> elementAtOrNullAsync<A>(int index, FxAsyncIterable<A> iterable) T? Fx.elementAtOrNull(int index) // sync chain: inherited Iterable method A? nth<A>(int index, Iterable<A> iterable) // FxTS alias

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 nth — they're the same operator. A negative index, or one past the end, simply yields null; 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. 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'.

Related: head — shorthand for elementAtOrNull(0, ...) · last — the final element · find — locate by predicate instead of index · slice — pull a whole range