The `lastWhere` method in Dart returns the last element that satisfies the given predicate test.
The syntax of Runes.lastWhere() method is:
int lastWhere(bool test(int element), { int orElse() })
This lastWhere() method of Runes returns the last element that satisfies the given predicate test
.
Parameter | Optional/Required | Description |
---|---|---|
test | required | The predicate function that takes an integer element and returns a boolean value. |
orElse | optional | An optional function that returns a default value if no element is found. |
Runes.lastWhere() returns value of type int
.
In this example,
numbers
containing integers.lastWhere()
method with a predicate function that checks for even numbers.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
int lastEven = numbers.lastWhere((element) => element % 2 == 0);
print(lastEven);
}
4
In this example,
words
containing strings.lastWhere()
method with a predicate function that checks for words longer than 5 characters.void main() {
List<String> words = ['apple', 'banana', 'cherry'];
String lastLong = words.lastWhere((word) => word.length > 5, orElse: () => 'No long word found');
print(lastLong);
}
cherry
In this example,
uniqueNumbers
containing integers.lastWhere()
method with a predicate function that checks for positive numbers.void main() {
Set<int> uniqueNumbers = {1, 2, 3};
int lastPositive = uniqueNumbers.lastWhere((number) => number > 0, orElse: () => -1);
print(lastPositive);
}
3
In this Dart tutorial, we learned about lastWhere() method of Runes: the syntax and few working examples with output and detailed explanation for each example.