Dart – Add Element to Set

To add an element or value to a Set in Dart, call add() method on this Set and pass the element as argument to it. Set.add() method adds the element to the Set, if it is not present, and returns a boolean value of true. If the element is already present, then add() method returns false.

Syntax

The syntax to add element to Set mySet is

</>
Copy
mySet.add(element)

Examples

In the following program, we take a Set with three elements, and adds a new element to the Set.

main.dart

</>
Copy
void main() {
  var mySet = {'apple', 'banana', 'cherry'};
  var element = 'mango';
  if (mySet.add(element)) {
    print('Element added to the set successfully.');
  } else {
    print('Element is already present inside the set.');
  }
}

Output

Element added to the set successfully.

Now, let us try to add an element, that is already present in the Set.

main.dart

</>
Copy
void main() {
  var mySet = {'apple', 'banana', 'cherry'};
  var element = 'banana';
  if (mySet.add(element)) {
    print('Element added to the set successfully.');
  } else {
    print('Element is already present inside the set.');
  }
}

Output

Element is already present inside the set.

Let us take the first example program, and print the Set before and after adding the element.

main.dart

</>
Copy
void main() {
  var mySet = {'apple', 'banana', 'cherry'};
  var element = 'mango';

  print('Original Set  : $mySet');
  mySet.add(element);
  print('Resulting Set : $mySet');
}

Output

Original Set  : {apple, banana, cherry}
Resulting Set : {apple, banana, cherry, mango}

Conclusion

In this Dart Tutorial, we learned how to add an element to a Set in Dart, with examples.