Dart List toSet()
Syntax & Examples


Syntax of List.toSet()

The syntax of List.toSet() method is:

 Set<E> toSet() 

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

Return Type

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



✐ Examples

1 Get unique numbers from the list

In this example,

  1. We create a list named numbers containing integers including duplicates.
  2. We then use the toSet() method on numbers to get a set of unique elements.
  3. The result is a set containing only unique numbers.
  4. We print the unique numbers to standard output.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3, 4, 5, 5];
  Set<int> uniqueNumbers = numbers.toSet();
  print('Unique numbers: $uniqueNumbers');
}

Output

Unique numbers: {1, 2, 3, 4, 5}

2 Get unique characters from the list

In this example,

  1. We create a list named characters containing strings including duplicates.
  2. We then use the toSet() method on characters to get a set of unique elements.
  3. The result is a set containing only unique characters.
  4. We print the unique characters to standard output.

Dart Program

void main() {
  List<String> characters = ['a', 'b', 'c', 'a', 'c'];
  Set<String> uniqueChars = characters.toSet();
  print('Unique characters: $uniqueChars');
}

Output

Unique characters: {a, b, c}

3 Get unique fruits from the list

In this example,

  1. We create a list named fruits containing strings including duplicates.
  2. We then use the toSet() method on fruits to get a set of unique elements.
  3. The result is a set containing only unique fruits.
  4. We print the unique fruits to standard output.

Dart Program

void main() {
  List<String> fruits = ['apple', 'banana', 'cherry', 'banana'];
  Set<String> uniqueFruits = fruits.toSet();
  print('Unique fruits: $uniqueFruits');
}

Output

Unique fruits: {apple, banana, cherry}

Summary

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