flutter
/

Dart Set – Complete Guide with Examples

Last Sync: Today

On this page

23
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

flutter

Dart Set – Complete Guide with Examples

What is a Set in Dart?

A Set is an unordered collection of unique items. Unlike a List, a Set cannot contain duplicate elements. This makes Sets ideal for tasks where you need to ensure uniqueness, such as storing a collection of tags, IDs, or any items where duplicates are not allowed. Dart's Set is implemented as a hash table, so most operations (add, remove, contains) are efficient.

Creating Sets

Dart provides several ways to create sets, depending on your needs.

  1. Set Literal

DARTRead-only
1
void main() {
  var fruits = {'apple', 'banana', 'orange'}; // Set<String>
  Set<int> numbers = {1, 2, 3, 4};            // explicit type
  print(fruits); // {apple, banana, orange}
}

  1. Empty Set

DARTRead-only
1
void main() {
  var emptySet = <String>{};      // empty Set<String>
  Set<int> anotherEmpty = {};     // also empty
}

⚠️ Important: Using {} alone creates a Map, not a Set. Always specify a type parameter or use a type annotation to create an empty Set.

  1. Using Set.from()

DARTRead-only
1
void main() {
  var list = [1, 2, 3, 2, 1];
  var setFromList = Set.from(list); // {1, 2, 3}
}

  1. Using Set.of()

DARTRead-only
1
void main() {
  var set = Set.of([1, 2, 3, 2]); // {1, 2, 3}
}

  1. Using Set.identity()

Creates an identity‑based set, which uses identical() rather than == for equality checks. Useful when you need to distinguish objects even if their content is the same.

DARTRead-only
1
void main() {
  var set = Set.identity();
  var a = Object();
  var b = Object();
  set.add(a);
  set.add(b);
  print(set.length); // 2 (different objects)
}

  1. Unmodifiable Set

DARTRead-only
1
void main() {
  var fixed = Set.unmodifiable({1, 2, 3});
  // fixed.add(4); // Throws UnsupportedError
}

Adding Elements

DARTRead-only
1
void main() {
  var set = <int>{};
  set.add(1);          // {1}
  set.add(2);          // {1, 2}
  set.add(1);          // still {1, 2} – duplicate ignored
  set.addAll([3, 4]);  // {1, 2, 3, 4}
}

Removing Elements

DARTRead-only
1
void main() {
  var set = {1, 2, 3, 4, 5};
  set.remove(3);            // {1, 2, 4, 5}
  set.removeAll({2, 4});    // {1, 5}
  set.retainAll({1});       // keep only elements in {1} → {1}
  set.clear();              // {}
}

Checking for Elements

DARTRead-only
1
void main() {
  var set = {'a', 'b', 'c'};
  print(set.contains('b'));      // true
  print(set.containsAll(['a', 'c'])); // true
  print(set.isEmpty);            // false
  print(set.isNotEmpty);         // true
  print(set.length);             // 3
}

Set Operations (Mathematical)

Sets support mathematical set operations: union, intersection, and difference.

Union

DARTRead-only
1
void main() {
  var a = {1, 2, 3};
  var b = {3, 4, 5};
  var union = a.union(b); // {1, 2, 3, 4, 5}
}

Intersection

DARTRead-only
1
void main() {
  var a = {1, 2, 3};
  var b = {3, 4, 5};
  var intersection = a.intersection(b); // {3}
}

Difference

DARTRead-only
1
void main() {
  var a = {1, 2, 3, 4};
  var b = {3, 4, 5};
  var difference = a.difference(b); // {1, 2}
}

Iterating Over a Set

DARTRead-only
1
void main() {
  var set = {'apple', 'banana', 'cherry'};
  
  // for-in loop
  for (var fruit in set) {
    print(fruit);
  }
  
  // forEach
  set.forEach((fruit) => print(fruit));
}

Converting Set to List

DARTRead-only
1
void main() {
  var set = {3, 1, 2};
  var list = set.toList(); // [3, 1, 2] (order not guaranteed)
  list.sort();             // [1, 2, 3]
}

Set Properties

    • length – number of elements.
    • isEmpty – true if the set has no elements.
    • isNotEmpty – true if the set has at least one element.
    • first – first element in iteration order (throws if empty).
    • last – last element in iteration order (throws if empty).
    • hashCode – the hash code of the set.

Useful Set Methods

    • add(element) – adds an element if not already present.
    • addAll(iterable) – adds all elements from an iterable.
    • remove(element) – removes a single element.
    • removeAll(iterable) – removes all elements in the iterable.
    • retainAll(iterable) – keeps only elements present in the iterable.
    • clear() – removes all elements.
    • contains(element) – checks if an element exists.
    • containsAll(iterable) – checks if all elements exist.
    • difference(other) – returns a new set with elements not in other.
    • intersection(other) – returns a new set with common elements.
    • union(other) – returns a new set with elements from both sets.
    • lookup(element) – returns the element if found, else null (useful with custom objects).
    • elementAt(index) – returns the element at a given position in iteration order (slow for large sets).

Collection If and For

Just like lists, sets support collection if and for for conditional and computed elements.

DARTRead-only
1
void main() {
  bool includeExtra = true;
  var numbers = {1, 2, if (includeExtra) 3, 4}; // {1, 2, 3, 4}
  
  var doubled = {for (var n in [1, 2, 3]) n * 2}; // {2, 4, 6}
}

Complete Example

DARTRead-only
1
void main() {
  // Create two sets of numbers
  var setA = {1, 2, 3, 4};
  var setB = {3, 4, 5, 6};
  
  // Union – all unique elements
  var union = setA.union(setB);
  print('Union: $union'); // {1, 2, 3, 4, 5, 6}
  
  // Intersection – common elements
  var intersection = setA.intersection(setB);
  print('Intersection: $intersection'); // {3, 4}
  
  // Difference – elements in A but not in B
  var difference = setA.difference(setB);
  print('Difference A - B: $difference'); // {1, 2}
  
  // Check if an element exists
  if (setA.contains(2)) {
    print('SetA contains 2');
  }
  
  // Convert to list and sort
  var listFromSet = setA.toList()..sort();
  print('Sorted list: $listFromSet');
}

When to Use a Set

    • When you need to store unique elements (no duplicates).
    • For fast lookups (contains is O(1)).
    • For mathematical set operations (union, intersection, difference).
    • When order doesn't matter.
    • For removing duplicates from a list.

Key Takeaways

    • Sets are unordered collections of unique items.
    • Use {} with a type argument to create a set literal.
    • Use Set.from(), Set.of(), Set.identity(), or Set.unmodifiable() for specialised sets.
    • Add elements with add() and addAll().
    • Remove elements with remove(), removeAll(), retainAll(), and clear().
    • Perform mathematical operations: union(), intersection(), difference().
    • Iterate with for‑in or forEach.
    • Sets are perfect for ensuring uniqueness and fast lookups.

Try it yourself

void main() {
  // Create a set of fruits
  var fruits = {'apple', 'banana', 'mango'};
  
  // Try to add a duplicate
  fruits.add('apple'); // ignored
  print('Fruits: $fruits');
  
  // Check if 'banana' exists
  print('Contains banana? ${fruits.contains('banana')}');
  
  // Add more fruits
  fruits.addAll(['orange', 'grape']);
  print('Updated fruits: $fruits');
}

Test Your Knowledge

Q1
of 4

What is the output of this code? void main() { var set = {1, 2, 3}; set.add(2); print(set.length); }

A
2
B
3
C
4
D
Error
Q2
of 4

Which method returns a new set containing elements that are in both sets?

A
union()
B
intersection()
C
difference()
D
retainAll()
Q3
of 4

How do you create an empty set of strings?

A
{}
B
Set()
C
<String>{}
D
String{}
Q4
of 4

What does `setA.difference(setB)` return?

A
Elements that are in setA but not in setB
B
Elements that are in setB but not in setA
C
Elements in either set
D
Elements common to both

Frequently Asked Questions

What is the difference between a Set and a List in Dart?

A List is an ordered collection that can contain duplicate elements. A Set is an unordered collection that automatically eliminates duplicates. Sets are optimized for fast membership testing (using contains), while Lists preserve order and allow indexed access.

How do I remove duplicates from a list?

Convert the list to a set and then back to a list: var uniqueList = list.toSet().toList();. This works because sets only keep unique elements.

How do I check if an element exists in a set?

Use the contains() method: if (mySet.contains('apple')) { ... }. This is very efficient (usually O(1)).

Can I get an element by index from a set?

Sets are unordered, so they don't have indices. You can use elementAt(index), but this is slow for large sets because it iterates to find the element. If you need indexed access, consider using a List.

What is the difference between `union`, `intersection`, and `difference`?

union returns a new set containing all elements from both sets (no duplicates). intersection returns a new set with elements that are present in both sets. difference returns a new set with elements that are in the first set but not in the second.

How do I create a copy of a set?

You can create a copy using the spread operator: var copy = {...originalSet};, or using Set.from(originalSet), or Set.of(originalSet). All create a new set with the same elements.

Are Dart sets ordered?

By default, the Set implementation in Dart (when using {} literals) is LinkedHashSet, which maintains insertion order. However, you should not rely on order for logic, as other set implementations (like HashSet) are unordered. If you need guaranteed order, use a LinkedHashSet explicitly.

Can a set contain `null`?

Yes, a set can contain null as an element. For example, var set = {1, null, 3}; is valid. The set will treat null as a unique element (you can only have one null).

Previous

dart list

Next

dart map

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.