Dart Set toSet()
Syntax & Examples


Syntax of toSet()

The syntax of Set.toSet() method is:

 Set<E> toSet() 

This toSet() method of Set creates a Set containing the same elements as this iterable.

Return Type

Set.toSet() returns value of type Set<E>.



✐ Examples

1 Creating a copy of a Set of integers

In this example,

  1. We create a Set numbersSett with values 1, 2, 3, 4.
  2. We use the toSet() method to convert numbersSet to a Set numbersSetCopy.
  3. We print the resulting numbersSetCopy.

Dart Program

void main() {
  Set<int> numbersSet = {1, 2, 3, 4};
  Set<int> numbersSetCopy = numbersSet.toSet();
  print(numbersSetCopy);
}

Output

{1, 2, 3, 4}

2 Copying a Set of strings to another Set

In this example,

  1. We create a Set wordsSet with values 'apple', 'banana', 'cherry'.
  2. We use the toSet() method to convert wordsSet to a Set wordsSetCopy.
  3. We print the resulting wordsSetCopy.

Dart Program

void main() {
  Set<String> wordsSet = {'apple', 'banana', 'cherry'};
  Set<String> wordsSetCopy = wordsSet.toSet();
  print(wordsSetCopy);
}

Output

{apple, banana, cherry}

Summary

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