Skip to content
AgileLogics
4 min read

Sets

Prerequisites: Maps

A set is a collection where each value appears at most once. Checking whether a set contains a value is very fast, even for large sets.

void main() {
  final tags = {'dart', 'flutter', 'dart', 'mobile'};
  print(tags);
  print(tags.length);
  print(tags.contains('flutter'));

  tags.add('web');
  tags.remove('mobile');
  print(tags);

  final a = {1, 2, 3, 4};
  final b = {3, 4, 5};
  print(a.intersection(b));
  print(a.union(b));
  print(a.difference(b));
}
{dart, flutter, mobile}
3
true
{dart, flutter, web}
{3, 4}
{1, 2, 3, 4, 5}
{1, 2}

The duplicate 'dart' is stored once. Dart's default sets keep insertion order.

An empty set needs a type, because {} on its own means an empty map:

final seen = <String>{};   // an empty Set<String>
final lookup = {};         // an empty Map<dynamic, dynamic>

Use a set when you only care about membership ("have we seen this before?"), and a list when order or duplicates matter. toSet() removes duplicates from a list: [1, 1, 2].toSet() is {1, 2}.