本页尚未翻译,因此以英文显示。 参与翻译

distinct

Removes duplicate values, keeping the first occurrence of each and preserving order.

Iterable<A> distinct<A>(Iterable<A> iterable) FxAsyncIterable<A> distinctAsync<A>(FxAsyncIterable<A> iterable) Fx<T> Fx.distinct() // chain FxAsync<T> FxAsync.distinct() Iterable<A> uniq<A>(Iterable<A> iterable) // FxTS alias

Lecture

distinct walks the iterable once, keeping a Set of values already seen, and yields each element only the first time it shows up. distinct is the Dart-idiomatic name; fxdart also accepts the FxTS spelling uniq — they're the same operator. It's implemented as uniqBy((a) => a, iterable) — the identity key — so if you ever need to dedupe by something other than equality of the whole value, reach for uniqBy instead.

It's lazy and streaming: the Set only grows as elements are pulled, so it never buffers the whole source up front. Order is preserved — the first occurrence of a value is what survives, not the last.

On the async side, distinctAsync is safe to combine with .concurrent(n) as long as the concurrency lives in an upstream fetch stage: fetch with .map(...).concurrent(n) first, then apply .distinct() to the already-resolved, in-order results, as in Demo 2.

Demo 1 · Basics

Demo 2 · Async, with concurrency upstream

Try it yourself

Exercise: use distinct to remove duplicate tags, preserving first-seen order.

Related: uniqBy — dedupe by a computed key · difference — remove elements found in another iterable · intersection — keep only shared elements · compact — drop nulls