Dart Set clear()
Syntax & Examples
Set.clear() method
The `clear` method in Dart removes all elements from a Set.
Syntax of Set.clear()
The syntax of Set.clear() method is:
void clear()
This clear() method of Set removes all elements in the set.
Return Type
Set.clear() returns value of type void
.
✐ Examples
1 Clearing a set of integers
In this example,
- We create a Set variable
numbers
containing integer elements. - We print the set before clearing it.
- We use the
clear()
method to remove all elements from the set. - We print the set after clearing it to standard output.
Dart Program
void main() {
Set<int> numbers = {1, 2, 3, 4, 5};
print('Before clearing: $numbers');
numbers.clear();
print('After clearing: $numbers');
}
Output
Before clearing: {1, 2, 3, 4, 5} After clearing: {}
2 Clearing a set of strings
In this example,
- We create a Set variable
fruits
containing string elements. - We print the set before clearing it.
- We use the
clear()
method to remove all elements from the set. - We print the set after clearing it to standard output.
Dart Program
void main() {
Set<String> fruits = {'apple', 'banana', 'orange', 'kiwi'};
print('Before clearing: $fruits');
fruits.clear();
print('After clearing: $fruits');
}
Output
Before clearing: {apple, banana, orange, kiwi} After clearing: {}
Summary
In this Dart tutorial, we learned about clear() method of Set: the syntax and few working examples with output and detailed explanation for each example.