What is the ListQueue.lastWhere() method in Dart?

ListQueue is a list based on Queue.

The lastWhere method returns the last element present in the queue that satisfies the provided test condition.

The lastWhere method loops the queue elements from end to start and checks each element against the provided test condition. If any of the elements satisfies the test condition, that element is returned.

Syntax

E lastWhere(bool test(E el),{E orElse()?})

Argument

This method takes two arguments.

  1. test: This is a predicatePredicate is a functional interface, which takes one argument and returns either true or false, based on the defined condition. function that is checked against the elements of the queue.
  2. orElse: This is a function that is invoked when no element of the queue satisfies the passed test predicate function. The value returned from this orElse method is returned as the return value of the lastWhere method. This is an optional argument.

Note: If no element matches the test condition and the orElse method is omitted, a state errorBad state: No element will be thrown.

Return value

This method returns the last element that satisfies the provided test condition. If no element satisfies the condition, then the orElse function argument is invoked, and the value returned from that function is returned.

Code

The code given below shows us how to use the lastWhere method:

import 'dart:collection';
void main() {
// create a queue
ListQueue queue = new ListQueue();
// add 3 elements to the queue
queue.add(10);
queue.add(20);
queue.add(30);
print('The queue is : $queue');
// Get the last element which is greater than 10
var result = queue.lastWhere( (e)=> e > 10 );
print('The last element which is greater than 10 : $result');
// Get the last element which is less than 0
result = queue.lastWhere( (e)=> e < 0, orElse: ()=> null);
print('The last element which is less than 0: $result');
}

Explanation

In the code given above:

  • In line 1, we import the collection library.

  • In line 4, we create a ListQueue with the name queue.

  • In lines 7–8, we use the add method to add three elements 10,20,30 to the queue. Now, the queue is {10,20,30}.

  • In line 13, we use the lastWhere method with a predicate function. The predicate function checks if element is greater than 10. In our case, the element 30 is the last element that is greater than 10. Hence, 30 is returned as a result.

  • In line 17, we use the lastWhere method with a predicate and an orElse function. The predicate function checks if the element is negative. In our case, all the queue elements are positive, so the orElse method is invoked and we return null from the orElse method.

Free Resources