Dart Set whereType()
Syntax & Examples
Set.whereType() method
The `whereType` method in Dart returns a new lazy iterable containing all elements of type T from the set.
Syntax of Set.whereType()
The syntax of Set.whereType() method is:
Iterable<T> whereType<T>()
This whereType() method of Set returns a new lazy Iterable with all elements that have type T.
Return Type
Set.whereType() returns value of type Iterable<T>
.
✐ Examples
1 Filter strings from a mixed set
In this example,
- We create a Set
mixedSet
with elements of various types. - We use the
whereType()
method with typeString
to filter only string elements. - The method returns a new iterable containing only the string elements.
- We print the result to standard output.
Dart Program
void main() {
Set<dynamic> mixedSet = {1, 'apple', true, 3.14, 'banana'};
var result = mixedSet.whereType<String>();
print('Result: $result');
}
Output
Result: {apple, banana}
2 Filter integers from an object set
In this example,
- We create a Set
objectSet
with elements of various types. - We use the
whereType()
method with typeint
to filter only integer elements. - The method returns a new iterable containing only the integer elements.
- We print the result to standard output.
Dart Program
void main() {
Set<Object> objectSet = {1, 'apple', true, 3.14, 'banana'};
var result = objectSet.whereType<int>();
print('Result: $result');
}
Output
Result: {1}
Summary
In this Dart tutorial, we learned about whereType() method of Set: the syntax and few working examples with output and detailed explanation for each example.