Dart Tutorials

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

ParameterOptional/RequiredDescription
testrequiredthe predicate function to test each element
orElseoptionala 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,

  1. We create a list numbers containing integers.
  2. We then use the lastWhere() method with a predicate to find the last even number.
  3. 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,

  1. We create a list fruits containing strings.
  2. We use the lastWhere() method with a length condition to find the last long name, or a default value if none is found.
  3. 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,

  1. We create a list prices containing double values.
  2. We use the lastWhere() method with a condition to find the last high price, or a default value if none is found.
  3. 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.