Dart Tutorials

Dart List whereType()
Syntax & Examples

Syntax of List.whereType()

The syntax of List.whereType() method is:

 Iterable<T> whereType<T>() 

This whereType() method of List creates a new lazy Iterable with all elements that have type T.

Return Type

List.whereType() returns value of type Iterable<T>.



✐ Examples

1 Filter integers from a mixed list

In this example,

  1. We create a list named mixedList containing elements of various types.
  2. We then call the whereType() method on mixedList, specifying the type int as the filter condition.
  3. The resulting iterable result contains only the elements that are of type int.
  4. We print the result to standard output.

Dart Program

void main() {
  List<Object> mixedList = [1, 'two', 3.0, true];
  var result = mixedList.whereType<int>();
  print(result); // Output: [1]
}

Output

(1, 3)

2 Filter strings from a mixed list

In this example,

  1. We create a list named mixedList containing elements of various types.
  2. We then call the whereType() method on mixedList, specifying the type String as the filter condition.
  3. The resulting iterable result contains only the elements that are of type String.
  4. We print the result to standard output.

Dart Program

void main() {
  List<Object> mixedList = [1, 'two', 3.0, true];
  var result = mixedList.whereType<String>();
  print(result); // Output: [two]
}

Output

[two]

3 Filter doubles from a mixed list

In this example,

  1. We create a list named mixedList containing elements of various types.
  2. We then call the whereType() method on mixedList, specifying the type double as the filter condition.
  3. The resulting iterable result contains only the elements that are of type double.
  4. We print the result to standard output.

Dart Program

void main() {
  List<Object> mixedList = [1, 'two', 3.0, true];
  var result = mixedList.whereType<double>();
  print(result); // Output: [3.0]
}

Output

(1, 3)

Summary

In this Dart tutorial, we learned about whereType() method of List: the syntax and few working examples with output and detailed explanation for each example.