Dart List firstWhere()
Syntax & Examples
Syntax of List.firstWhere()
The syntax of List.firstWhere() method is:
E firstWhere(bool test(E element), {E orElse()?})
This firstWhere() method of List the first element that satisfies the given predicate test
.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
test | required | a function that returns true for the desired element |
orElse | optional | a function that returns a default value if no element is found |
Return Type
List.firstWhere() returns value of type E
.
✐ Examples
1 Find the first even number in a list
In this example,
- We create a list named
numbers
containing integers. - We use the
firstWhere()
method with a function that checks for even numbers. - The first even number in
numbers
is returned. - We print the first even number to standard output.
Dart Program
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
int firstEven = numbers.firstWhere((element) => element % 2 == 0);
print('First even number: $firstEven');
}
Output
First even number: 2
2 Find the first word longer than 5 characters in a list
In this example,
- We create a list named
words
containing strings. - We use the
firstWhere()
method with a function that checks for words longer than 5 characters. - The first word longer than 5 characters in
words
is returned, or a default message if no such word exists. - We print the result to standard output.
Dart Program
void main() {
List<String> words = ['apple', 'banana', 'cherry'];
String longWord = words.firstWhere((element) => element.length > 5, orElse: () => 'No long word found');
print('Long word: $longWord');
}
Output
Long word: banana
3 Find the first even number in an empty list with a default value
In this example,
- We create an empty list named
emptyList
. - We use the
firstWhere()
method with a function that checks for even numbers and a default value function. - Since the list is empty, the default value (-1) is returned.
- We print the default element to standard output.
Dart Program
void main() {
List<int> emptyList = [];
int defaultElement = emptyList.firstWhere((element) => element % 2 == 0, orElse: () => -1);
print('Default element: $defaultElement');
}
Output
Default element: -1
Summary
In this Dart tutorial, we learned about firstWhere() method of List: the syntax and few working examples with output and detailed explanation for each example.