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

ifEmpty

Switches to a fallback when the pipeline turns out to be empty — decided lazily, at iteration time.

Iterable<A> ifEmpty<A>(Iterable<A> Function() fallback, Iterable<A> iterable) Iterable<A> defaultIfEmpty<A>(A value, Iterable<A> iterable) FxAsyncIterable<A> ifEmptyAsync<A>(FxAsyncIterable<A> Function() fallback, FxAsyncIterable<A> iterable) FxAsyncIterable<A> defaultIfEmptyAsync<A>(FutureOr<A> value, FxAsyncIterable<A> iterable) Fx<T> Fx<T>.ifEmpty(Iterable<T> Function() fallback) / .defaultIfEmpty(T value) // chain (sync) FxAsync<T> FxAsync<T>.ifEmpty(FxAsyncIterable<T> Function() fallback) / .defaultIfEmpty(FutureOr<T> value) // chain (async)

Lecture

A pipeline that might produce nothing usually forces a detour: materialize it, test isEmpty, branch. That breaks the chain and — worse — runs the pipeline before you meant to. ifEmpty(fallback) folds the branch into the pipeline itself: values pass through untouched, and only if the source finishes without yielding anything does the fallback iterable take over. The fallback function is not even called otherwise — lazy in both directions.

defaultIfEmpty(value) is the one-value shorthand: the placeholder row, the 0 for an empty report, the "no results" marker. Both compose anywhere in the chain, which matters after aggressive filtering — the emptiness is decided by whatever reaches this point, not by the original source.

fxdart extension (no FxTS counterpart), after Rx's switchIfEmpty / defaultIfEmpty. The async forms accept an async fallback chain and a Future default, and compose with concurrent.

Demo 1 · A default for the empty report

Demo 2 · Fallback source, never touched otherwise

Try it yourself

Exercise: search with a fallback query.

Related: filter — the usual reason a chain ends up empty · concat — appending unconditionally · headnull instead of a fallback, for a single value