thumbnail

Sets in Dart

Published on 29 March 2020
Last Updated on 29 March 2020

What are Sets in Dart

A set is a unique collection of items added in an unordered list.

Program that demonstrates how to use Sets in Dart

void main(List<String> args) {
  // a set of alphabet
  var alphabet = {'a', 'b', 'c', 'd'};
  print('alphabet is ${alphabet}');

  // an empty set of numbers
  var numberSet = <int>{};
  print('numberSet is ${numberSet}');

  // a set of even numbers
  var evenNumberSet = <int>{2, 4};
  print('evenNumberSet is ${evenNumberSet}');

  // adding items to an empty set
  numberSet.add(0);
  numberSet.add(2);

  // adding even numbers to set of numbers
  numberSet.addAll(evenNumberSet);

  print('evenNumberSet is ${evenNumberSet}');

  // using .length to read how many items are there in the set
  print('numberSet has ${numberSet.length} items in it.');

  // sets that are compile time constant
  const fruits = {
    'apple',
    'orange',
    'banana',
    'watermelon',
  };
  print('fruits set is ${fruits}');
}

Running above program will produce following output:

alphabet is {a, b, c, d}
numberSet is {}
evenNumberSet is {2, 4}
evenNumberSet is {2, 4}
numberSet has 3 items in it.
fruits set is {apple, orange, banana, watermelon}

Defining an empty set in dart

As shown in program given below, an empty set can be defined by using following syntax:

// an empty set of numbers
var numberSet = <int>{};

Adding new item or a set of items to an existing set

Use following syntax to add new elements to an existing set of items.

numberSet.add(0);
numberSet.add(2);
numberSet.addAll(evenNumberSet);

Lists that are compile time constant

Use following syntax to define a list of elements that are compile time constants.

const fruits = {
  'apple',
  'orange',
  'banana',
  'watermelon',
};