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,
- We create a list named
mixedList
containing elements of various types. - We then call the
whereType()
method onmixedList
, specifying the typeint
as the filter condition. - The resulting iterable
result
contains only the elements that are of typeint
. - 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,
- We create a list named
mixedList
containing elements of various types. - We then call the
whereType()
method onmixedList
, specifying the typeString
as the filter condition. - The resulting iterable
result
contains only the elements that are of typeString
. - 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,
- We create a list named
mixedList
containing elements of various types. - We then call the
whereType()
method onmixedList
, specifying the typedouble
as the filter condition. - The resulting iterable
result
contains only the elements that are of typedouble
. - 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.