What is the ListQueue.lastWhere() method in Dart?
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.
Syntax
E lastWhere(bool test(E el),{E orElse()?})
Argument
This method takes two arguments.
test: This is a function that is checked against the elements of the queue.predicate Predicate is a functional interface, which takes one argument and returns either true or false, based on the defined condition. orElse: This is a function that is invoked when no element of the queue satisfies the passedtestpredicate function. The value returned from thisorElsemethod is returned as the return value of thelastWheremethod. 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
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 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');}
Explanation
In the code given above:
-
In line 1, we import the
collectionlibrary. -
In line 4, we create a
ListQueuewith the namequeue. -
In lines 7–8, we use the
addmethod to add three elements10,20,30to the queue. Now, the queue is{10,20,30}. -
In line 13, we use the
lastWheremethod with a predicate function. The predicate function checks if element is greater than 10. In our case, the element30is the last element that is greater than 10. Hence,30is returned as a result. -
In line 17, we use the
lastWheremethod with a predicate and anorElsefunction. The predicate function checks if the element is negative. In our case, all the queue elements are positive, so theorElsemethod is invoked and we returnnullfrom theorElsemethod.