What is the List lastWhere() method in Dart?

List lastWhere() method

The lastWhere() method returns the last item in the list that satisfies the condition.

Syntax

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

Return value

The method lastWhere() iterates through the list and returns the last item to satisfy the given condition.

The orElse() method is invoked if no element satisfies the condition.

Code

The following code shows how to use the method lastWhere() in Dart:

void main(){
// Creating list fruits
List<String> fruits = ['Apple', 'Lemon', 'Avocado', 'Orange', ' Lime', 'Lychee'];
// iterate through the list
// Returns the last item that starts with 'L'
// the orElse() is invoke if not found
var fav = fruits.lastWhere((item) => item.startsWith('L'),
orElse: () => 'Fruit not available');
// Display result
print(fav);
}

If orElse() method is not specified, a StateError is thrown by default.

Code explanation

We create a list named fruits. Next, we iterate through the list using lastWhere() method which returns the last item that starts with ‘L’. The returned value is then stored in variable fav.

Note: The orElse() is invoked if the item is not found.

Free Resources