Dart Runes lastWhere()
Syntax & Examples

Runes.lastWhere() method

The `lastWhere` method in Dart returns the last element that satisfies the given predicate test.


Syntax of Runes.lastWhere()

The syntax of Runes.lastWhere() method is:

 int lastWhere(bool test(int element), { int orElse() }) 

This lastWhere() method of Runes returns the last element that satisfies the given predicate test.

Parameters

ParameterOptional/RequiredDescription
testrequiredThe predicate function that takes an integer element and returns a boolean value.
orElseoptionalAn optional function that returns a default value if no element is found.

Return Type

Runes.lastWhere() returns value of type int.



✐ Examples

1 Finding the last even number in a list

In this example,

  1. We create a list numbers containing integers.
  2. We use the lastWhere() method with a predicate function that checks for even numbers.
  3. We print the last even number found in the list.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3, 4, 5];
  int lastEven = numbers.lastWhere((element) => element % 2 == 0);
  print(lastEven);
}

Output

4

2 Finding the last long word in a list of strings

In this example,

  1. We create a list words containing strings.
  2. We use the lastWhere() method with a predicate function that checks for words longer than 5 characters.
  3. If no long word is found, we provide an orElse function to return a default value.
  4. We print the last long word found or the default value.

Dart Program

void main() {
  List<String> words = ['apple', 'banana', 'cherry'];
  String lastLong = words.lastWhere((word) => word.length > 5, orElse: () => 'No long word found');
  print(lastLong);
}

Output

cherry

3 Finding the last positive number in a set of numbers

In this example,

  1. We create a set uniqueNumbers containing integers.
  2. We use the lastWhere() method with a predicate function that checks for positive numbers.
  3. If no positive number is found, we provide an orElse function to return a default value.
  4. We print the last positive number found or the default value.

Dart Program

void main() {
  Set<int> uniqueNumbers = {1, 2, 3};
  int lastPositive = uniqueNumbers.lastWhere((number) => number > 0, orElse: () => -1);
  print(lastPositive);
}

Output

3

Summary

In this Dart tutorial, we learned about lastWhere() method of Runes: the syntax and few working examples with output and detailed explanation for each example.