ListQueueis a list based onQueue.
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.
E lastWhere(bool test(E el),{E orElse()?})
This method takes two arguments.
test: This is a 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
testcondition and theorElsemethod is omitted, awill be thrown. state error Bad state: No element
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.
The code given below shows us how to use the lastWhere method:
import 'dart:collection';void main() {// create a queueListQueue queue = new ListQueue();// add 3 elements to the queuequeue.add(10);queue.add(20);queue.add(30);print('The queue is : $queue');// Get the last element which is greater than 10var result = queue.lastWhere( (e)=> e > 10 );print('The last element which is greater than 10 : $result');// Get the last element which is less than 0result = queue.lastWhere( (e)=> e < 0, orElse: ()=> null);print('The last element which is less than 0: $result');}
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.