Dart Set()
Syntax & Examples
Set constructor
The `Set` constructor in Dart creates an empty Set.
Syntax of Set
The syntax of Set.Set constructor is:
Set()
This Set constructor of Set creates an empty Set.
✐ Examples
1 Adding numbers to a Set
In this example,
- We create a new empty Set called `numbers`.
- We add integers 1, 2, and 3 to the `numbers` Set using the `add` method.
- We then print the `numbers` Set, which shows the elements in the Set.
Dart Program
void main() {
Set<int> numbers = Set();
numbers.add(1);
numbers.add(2);
numbers.add(3);
print(numbers); // Output: {1, 2, 3}
}
Output
{1, 2, 3}
2 Adding characters to a Set
In this example,
- We create a new empty Set called `characters`.
- We add characters 'a', 'b', and 'c' to the `characters` Set using the `add` method.
- We then print the `characters` Set, which shows the characters in the Set.
Dart Program
void main() {
Set<String> characters = Set();
characters.add('a');
characters.add('b');
characters.add('c');
print(characters); // Output: {a, b, c}
}
Output
{a, b, c}
3 Adding strings to a Set
In this example,
- We create a new empty Set called `words`.
- We add strings 'apple', 'banana', and 'cherry' to the `words` Set using the `add` method.
- We then print the `words` Set, which shows the strings in the Set.
Dart Program
void main() {
Set<String> words = Set();
words.add('apple');
words.add('banana');
words.add('cherry');
print(words); // Output: {apple, banana, cherry}
}
Output
{apple, banana, cherry}
Summary
In this Dart tutorial, we learned about Set constructor of Set: the syntax and few working examples with output and detailed explanation for each example.