Dart Set.of()
Syntax & Examples
Set.of constructor
The `Set.of` constructor in Dart creates a Set from the provided elements in the iterable.
Syntax of Set.of
The syntax of Set.Set.of constructor is:
Set.of(Iterable<E> elements)This Set.of constructor of Set creates a Set from elements.
Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
elements | required | The iterable whose elements are used to create the Set. |
✐ Examples
1 Creating a Set from a list of numbers
In this example,
- We create a list of integers
numberswith the values [1, 2, 3, 4, 5]. - We use the
Set.ofconstructor to create a SetnumberSetfrom the list of numbers. - We then print the result to standard output.
Dart Program
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
Set<int> numberSet = Set.of(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,
- We create a string
characterswith the value 'hello'. - We split the string into individual characters and use the
Set.ofconstructor to create a SetcharSetfrom the characters. - We then print the result to standard output.
Dart Program
void main() {
String characters = 'hello';
Set<String> charSet = Set.of(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,
- We create a list of strings
wordswith the values ['apple', 'banana', 'cherry']. - We use the
Set.ofconstructor to create a SetwordSetfrom the list of words. - We then print the result to standard output.
Dart Program
void main() {
List<String> words = ['apple', 'banana', 'cherry'];
Set<String> wordSet = Set.of(words);
print('Word Set: $wordSet');
}Output
Word Set: {apple, banana, cherry}Summary
In this Dart tutorial, we learned about Set.of constructor of Set: the syntax and few working examples with output and detailed explanation for each example.