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
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
numbers
with the values [1, 2, 3, 4, 5]. - We use the
Set.from
constructor to create a SetnumberSet
from 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.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,
- We create a string
characters
with the value 'hello'. - We split the string into individual characters and use the
Set.from
constructor to create a SetcharSet
from the characters. - 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,
- We create a list of strings
words
with the values ['apple', 'banana', 'cherry']. - We use the
Set.from
constructor to create a SetwordSet
from 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.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.