Dart Set.from()
Syntax & Examples


Set.from constructor

The `Set.from` constructor in Dart creates a Set that contains all elements from the provided iterable.


Syntax of Set.from

The syntax of Set.Set.from constructor is:

Set.from(Iterable elements)

This Set.from constructor of Set creates a Set that contains all elements.

Parameters

ParameterOptional/RequiredDescription
elementsrequiredThe iterable whose elements are used to create the Set.


✐ Examples

1 Creating a Set from a list of numbers

In this example,

  1. We create a list of integers numbers with the values [1, 2, 3, 4, 5].
  2. We use the Set.from constructor to create a Set numberSet from the list of numbers.
  3. We then print the result to standard output.

Dart Program

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

Output

Number Set: {1, 2, 3, 4, 5}

2 Creating a Set from a string of characters

In this example,

  1. We create a string characters with the value 'hello'.
  2. We split the string into individual characters and use the Set.from constructor to create a Set charSet from the characters.
  3. We then print the result to standard output.

Dart Program

void main() {
  String characters = 'hello';
  Set<String> charSet = Set.from(characters.split(''));
  print('Character Set: $charSet');
}

Output

Character Set: {h, e, l, o}

3 Creating a Set from a list of strings

In this example,

  1. We create a list of strings words with the values ['apple', 'banana', 'cherry'].
  2. We use the Set.from constructor to create a Set wordSet from the list of words.
  3. We then print the result to standard output.

Dart Program

void main() {
  List<String> words = ['apple', 'banana', 'cherry'];
  Set<String> wordSet = Set.from(words);
  print('Word Set: $wordSet');
}

Output

Word Set: {apple, banana, cherry}

Summary

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