The syntax of List.lastWhere() method is:
E lastWhere(bool test(E element), {E orElse()?})
This lastWhere() method of List the last element that satisfies the given predicate test
.
Parameter | Optional/Required | Description |
---|---|---|
test | required | the predicate function to test each element |
orElse | optional | a function to return a default value if no element satisfies the predicate |
List.lastWhere() returns value of type E
.
In this example,
numbers
containing integers.lastWhere()
method with a predicate to find the last even number.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
int lastEven = numbers.lastWhere((element) => element % 2 == 0);
print('Last even number: $lastEven');
}
Last even number: 4
In this example,
fruits
containing strings.lastWhere()
method with a length condition to find the last long name, or a default value if none is found.void main() {
List<String> fruits = ['apple', 'banana', 'cherry'];
String lastLongName = fruits.lastWhere((element) => element.length > 5, orElse: () => 'No long names');
print('Last long name: $lastLongName');
}
Last long name: cherry
In this example,
prices
containing double values.lastWhere()
method with a condition to find the last high price, or a default value if none is found.void main() {
List<double> prices = [9.99, 19.99, 4.99];
double lastHighPrice = prices.lastWhere((element) => element > 10, orElse: () => 0.0);
print('Last high price: $lastHighPrice');
}
Last high price: 19.99
In this Dart tutorial, we learned about lastWhere() method of List: the syntax and few working examples with output and detailed explanation for each example.