Sets

A set in Dart is an unordered collection of unique items.Dart support for sets is provided by set literals and the Set type.

Version note: Although the Set type has always been a core part of Dart, set literals were introduced in Dart 2.2.

Here is a simple Dart set, created using a set literal:

  1. var halogens = {'fluorine', 'chlorine', 'bromine', 'iodine', 'astatine'};

Note: Dart infers that halogens has the type Set<String>. If you try to add the wrong type of value to the set, the analyzer or runtime raises an error. For more information, read about type inference.

To create an empty set, use {} preceded by a type argument,or assign {} to a variable of type Set:

  1. var names = <String>{};
  2. // Set<String> names = {}; // This works, too.
  3. // var names = {}; // Creates a map, not a set.

Set or map? The syntax for map literals is similar to that for set literals. Because map literals came first, {} defaults to the Map type. If you forget the type annotation on {} or the variable it’s assigned to, then Dart creates an object of type Map<dynamic, dynamic>.

Add items to an existing set using the add() or addAll() methods:

  1. var elements = <String>{};
  2. elements.add('fluorine');
  3. elements.addAll(halogens);

Use .length to get the number of items in the set:

  1. var elements = <String>{};
  2. elements.add('fluorine');
  3. elements.addAll(halogens);
  4. assert(elements.length == 5);

To create a set that’s a compile-time constant,add const before the set literal:

  1. final constantSet = const {
  2. 'fluorine',
  3. 'chlorine',
  4. 'bromine',
  5. 'iodine',
  6. 'astatine',
  7. };
  8. // constantSet.add('helium'); // Uncommenting this causes an error.

As of Dart 2.3, sets support spread operators ( and …?)and collection ifs and fors,just like lists do.For more information, see thelist spread operator andlist collection operator discussions.

For more information about sets, seeGenerics andSets.