Dart Set addAll()
Syntax & Examples


Syntax of Set.addAll()

The syntax of Set.addAll() method is:

 void addAll(Iterable<E> elements) 

This addAll() method of Set adds all elements to this Set.

Parameters

ParameterOptional/RequiredDescription
elementsrequiredAn Iterable containing elements to add to the Set.

Return Type

Set.addAll() returns value of type void.



✐ Examples

1 Adding numbers to a Set

In this example,

  1. We create a Set numSet with initial values {1, 2, 3}.
  2. We create a List numbersToAdd containing elements [4, 5, 6] to add to numSet.
  3. We use the addAll() method to add all elements from numbersToAdd to numSet.
  4. We print the updated numSet after addition.

Dart Program

void main() {
  Set<int> numSet = {1, 2, 3};
  List<int> numbersToAdd = [4, 5, 6];
  numSet.addAll(numbersToAdd);
  print(numSet);
}

Output

{1, 2, 3, 4, 5, 6}

2 Adding characters to a Set

In this example,

  1. We create a Set charSet with initial values {'a', 'b', 'c'}.
  2. We create a List charsToAdd containing elements ['d', 'e', 'f'] to add to charSet.
  3. We use the addAll() method to add all elements from charsToAdd to charSet.
  4. We print the updated charSet after addition.

Dart Program

void main() {
  Set<String> charSet = {'a', 'b', 'c'};
  List<String> charsToAdd = ['d', 'e', 'f'];
  charSet.addAll(charsToAdd);
  print(charSet);
}

Output

{a, b, c, d, e, f}

3 Adding strings to a Set

In this example,

  1. We create a Set wordSet with initial values {'hello', 'world'}.
  2. We create a List wordsToAdd containing elements ['open', 'source'] to add to wordSet.
  3. We use the addAll() method to add all elements from wordsToAdd to wordSet.
  4. We print the updated wordSet after addition.

Dart Program

void main() {
  Set<String> wordSet = {'hello', 'world'};
  List<String> wordsToAdd = ['open', 'source'];
  wordSet.addAll(wordsToAdd);
  print(wordSet);
}

Output

{hello, world, open, source}

Summary

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