Dung (Donny) Nguyen

Senior Software Engineer

Sets

Working with sets in Dart is quite simple and similar to working with lists, but with some key differences. A set is an unordered collection of unique items, which means it automatically removes duplicates.

Creating a Set

We can create a set using the Set constructor or a set literal.

// Using Set constructor
Set<int> numbers = Set<int>();

// Using set literal
Set<String> fruits = {'Apple', 'Banana', 'Cherry'};

Adding Elements to a Set

We can add elements to a set using the add and addAll methods.

fruits.add('Date');
fruits.addAll({'Elderberry', 'Fig'});

Accessing Elements

Since sets are unordered collections, we cannot access elements by their index. We can use methods like contains, forEach, and other collection methods to interact with the set.

bool hasBanana = fruits.contains('Banana'); // Check if 'Banana' is in the set

Removing Elements

We can remove elements from a set using the remove, removeAll, and clear methods.

fruits.remove('Banana'); // Removes 'Banana'
fruits.removeAll({'Date', 'Fig'}); // Removes 'Date' and 'Fig'
fruits.clear(); // Removes all elements from the set

Iterating Over a Set

We can iterate over a set using a forEach, for-in loop, or any other collection method.

// Using for-in loop
for (String fruit in fruits) {
  print(fruit);
}

// Using forEach
fruits.forEach((fruit) => print(fruit));

Other Useful Methods

Dart sets come with a variety of other useful methods, such as union, intersection, difference, and lookup.

Set<int> evens = {2, 4, 6, 8};
Set<int> odds = {1, 3, 5, 7};
Set<int> allNumbers = evens.union(odds); // Combines both sets

Set<int> intersection = evens.intersection({4, 5, 6}); // Finds common elements

Set<int> difference = evens.difference({4, 5, 6}); // Finds elements in evens but not in the other set

bool containsElement = evens.lookup(4) != null; // Checks if the set contains a specific element

Example

Here’s a small example demonstrating how to use sets in Dart:

void main() {
  Set<String> fruits = {'Apple', 'Banana', 'Cherry'};

  fruits.add('Date');
  fruits.add('Banana'); // Will not be added again since sets contain unique elements

  print(fruits); // Output: {Apple, Banana, Cherry, Date}

  fruits.remove('Cherry');
  print(fruits); // Output: {Apple, Banana, Date}

  for (String fruit in fruits) {
    print(fruit);
  }

  // Using set operations
  Set<int> evens = {2, 4, 6, 8};
  Set<int> odds = {1, 3, 5, 7};
  Set<int> allNumbers = evens.union(odds); // Union of evens and odds

  print(allNumbers); // Output: {1, 2, 3, 4, 5, 6, 7, 8}
}

This should give us a solid foundation to start working with sets in Dart.