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
.
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 |
List.firstWhere() returns value of type E
.
In this example,
numbers
containing integers.firstWhere()
method with a function that checks for even numbers.numbers
is returned.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
int firstEven = numbers.firstWhere((element) => element % 2 == 0);
print('First even number: $firstEven');
}
First even number: 2
In this example,
words
containing strings.firstWhere()
method with a function that checks for words longer than 5 characters.words
is returned, or a default message if no such word exists.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');
}
Long word: banana
In this example,
emptyList
.firstWhere()
method with a function that checks for even numbers and a default value function.void main() {
List<int> emptyList = [];
int defaultElement = emptyList.firstWhere((element) => element % 2 == 0, orElse: () => -1);
print('Default element: $defaultElement');
}
Default element: -1
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.