Find the last element that satisfies a test.
The lastWhere method returns the last element of an iterable that satisfies the given test function. If no element matches, it calls the optional orElse function, or throws a StateError if orElse is not provided.
The method iterates through all elements and keeps track of the last matching element, so it always iterates the entire iterable. For lists, this means checking every element from first to last.
LastWhere is useful when you need the most recent or final occurrence of an element matching a condition, such as finding the last error in a log or the last item meeting a threshold.
| Name | Description | Optional |
|---|---|---|
test |
A function that returns true for matching elements. | No |
orElse |
A function called when no element matches. Returns a default value. | Yes |
var numbers = [1, 2, 3, 4, 5, 6];
var last = numbers.lastWhere((n) => n.isEven);
print(last); // 6
var result = numbers.lastWhere(
(n) => n > 10,
orElse: () => -1,
);
print(result); // -1