Dart Set lastWhere()
Syntax & Examples


Set.lastWhere() method

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


Syntax of Set.lastWhere()

The syntax of Set.lastWhere() method is:

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

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

Parameters

ParameterOptional/RequiredDescription
testrequiredA function that takes an element of the iterable and returns a boolean value.
orElseoptionalA function that returns a default value if no element is found that satisfies the test.

Return Type

Set.lastWhere() returns value of type E.



✐ Examples

1 Finding the last even number

In this example,

  1. We create a List numbers with values [1, 2, 3, 4, 5].
  2. We use the lastWhere() method with a test function that finds the last even number.
  3. We print the result, which is the last even number in the list.

Dart Program

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

Output

4

2 Finding the last long word

In this example,

  1. We create a List words with values ['apple', 'banana', 'cherry'].
  2. We use the lastWhere() method with a test function that finds the last word with length greater than 5.
  3. If no such word is found, we return 'No long word found' using the orElse parameter.
  4. We print the result, which is the last long word or the default message.

Dart Program

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

Output

cherry

Summary

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