Skip to main content
A Set in Dart is an iterable collection of unique objects. It enforces element uniqueness by evaluating the equality of its items using their == operator and hashCode properties. Attempting to add a duplicate value to a Set is a no-op; the collection remains unchanged and no exception is thrown. By default, Dart set literals instantiate a LinkedHashSet, which maintains insertion order while providing amortized constant-time O(1) complexity for add, remove, and lookup operations.

Syntax and Initialization

Sets are typically created using set literals {} or explicitly typed constructors. Because Dart uses {} for both sets and maps, creating an empty set requires explicit type annotations to prevent the compiler from inferring a Map<dynamic, dynamic>.

Core Operations

The Set API provides standard collection mutations and lookups.

Mathematical Set Operations

Dart provides built-in methods for standard mathematical set theory operations, returning new Set instances without mutating the originals.

Alternative Implementations

While LinkedHashSet is the default, the dart:collection library provides alternative implementations with different performance and ordering guarantees:

Spread Operator and Control Flow

Sets fully support Dart’s spread operator (...), null-aware spread operator (...?), and collection if/for constructs for declarative composition.
Tired of Poor Dart Skills? Fix That With Deep Grasping!Learn More