Dart Set add()
Syntax & Examples


Set.add() method

The `add` method in Dart adds a value to a Set.


Syntax of Set.add()

The syntax of Set.add() method is:

 bool add(E value) 

This add() method of Set adds value to the set.

Parameters

ParameterOptional/RequiredDescription
valuerequiredThe value to be added to the set.

Return Type

Set.add() returns value of type bool.



✐ Examples

1 Adding an integer to a set of integers

In this example,

  1. We create a Set variable numbers containing integer elements.
  2. We use the add() method to add the value 4 to the set.
  3. We print whether the addition was successful and the updated set to standard output.

Dart Program

void main() {
  Set<int> numbers = {1, 2, 3};
  bool added = numbers.add(4);
  print('Value added successfully: $added');
  print('Updated set: $numbers');
}

Output

Value added successfully: true
Updated set: {1, 2, 3, 4}

2 Adding a string to a set of strings

In this example,

  1. We create a Set variable fruits containing string elements.
  2. We use the add() method to add the value 'kiwi' to the set.
  3. We print whether the addition was successful and the updated set to standard output.

Dart Program

void main() {
  Set<String> fruits = {'apple', 'banana', 'orange'};
  bool added = fruits.add('kiwi');
  print('Value added successfully: $added');
  print('Updated set: $fruits');
}

Output

Value added successfully: true
Updated set: {'apple', 'banana', 'orange', 'kiwi'}

Summary

In this Dart tutorial, we learned about add() method of Set: the syntax and few working examples with output and detailed explanation for each example.