firstWhereOrNull

Returns the first element for which a predicate is true, or null.

A? firstWhereOrNull<A>(bool Function(A a) f, Iterable<A> iterable) Future<A?> firstWhereOrNullAsync<A>(FutureOr<bool> Function(A a) f, FxAsyncIterable<A> iterable) T? Fx.firstWhereOrNull(bool Function(T a) f) // chain Future<T?> FxAsync.firstWhereOrNull(FutureOr<bool> Function(T a) f) // chain A? find<A>(bool Function(A a) f, Iterable<A> iterable) // FxTS alias

Lecture

firstWhereOrNull is the Dart-idiomatic name; fxdart also accepts the FxTS spelling find — they're the same operator. It's what head and filter look like fused together — in fact it's implemented as exactly that: head(filter(f, iterable)). That fusion is what makes it lazy and short-circuiting: it pulls elements one at a time, testing each against f, and stops the instant it finds a match. Nothing further downstream is ever touched.

Just like head, an unmatched search returns null rather than FxTS's undefined. It's available data-first, as an async variant, and as a method on both the sync and async chains.

Demo 1 · Basics

Demo 2 · Short-circuiting & async

Only 6 of a million elements are ever checked:

Try it yourself

Exercise: use firstWhereOrNull to get the first item with qty > 0, or null.

Related: findIndex — same search, returns a position · filter — every match, not just the first · head — what find is built from · matches — a ready-made shape-matching predicate