Dart List lastWhere()
Syntax & Examples
Syntax of List.lastWhere()
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
.
Parameters
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 |
Return Type
List.lastWhere() returns value of type E
.
✐ Examples
1 Get last even number
In this example,
- We create a list
numbers
containing integers. - We then use the
lastWhere()
method with a predicate to find the last even number. - The result is printed to standard output.
Dart Program
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
int lastEven = numbers.lastWhere((element) => element % 2 == 0);
print('Last even number: $lastEven');
}
Output
Last even number: 4
2 Get last long name in the list
In this example,
- We create a list
fruits
containing strings. - We use the
lastWhere()
method with a length condition to find the last long name, or a default value if none is found. - The result is printed to standard output.
Dart Program
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');
}
Output
Last long name: cherry
3 Get last high price in the list
In this example,
- We create a list
prices
containing double values. - We use the
lastWhere()
method with a condition to find the last high price, or a default value if none is found. - The result is printed to standard output.
Dart Program
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');
}
Output
Last high price: 19.99
Summary
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.