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,

  1. We create a Set mixedSet with elements of various types.
  2. We use the whereType() method with type String to filter only string elements.
  3. The method returns a new iterable containing only the string elements.
  4. 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,

  1. We create a Set objectSet with elements of various types.
  2. We use the whereType() method with type int to filter only integer elements.
  3. The method returns a new iterable containing only the integer elements.
  4. 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.