The syntax of List.lastIndexWhere() method is:
int lastIndexWhere(bool test(E element), [int? start])
This lastIndexWhere() method of List the last index in the list that satisfies the provided test
.
Parameter | Optional/Required | Description |
---|---|---|
test | required | a function that returns true for the desired element |
start | optional | the index to start searching from, defaults to the end of the list |
List.lastIndexWhere() returns value of type int
.
In this example,
numbers
containing the numbers [1, 2, 3, 4, 5]
.lastIndexWhere()
method with a test function that checks if the element is even.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
int lastIndex = numbers.lastIndexWhere((element) => element % 2 == 0); // Output: 3
print('Last index of even number: $lastIndex');
}
Last index of even number: 3
In this example,
characters
containing the characters ['a', 'b', 'c', 'd', 'e']
.lastIndexWhere()
method with a test function that checks if the element is equal to 'c'.void main() {
List<String> characters = ['a', 'b', 'c', 'd', 'e'];
int lastIndex = characters.lastIndexWhere((element) => element == 'c'); // Output: 2
print('Last index of character \'c\': $lastIndex');
}
Last index of character 'c': 2
In this example,
strings
containing the strings ['apple', 'banana', 'cherry', 'banana']
.lastIndexWhere()
method with a test function that checks if the element starts with 'b'.void main() {
List<String> strings = ['apple', 'banana', 'cherry', 'banana'];
int lastIndex = strings.lastIndexWhere((element) => element.startsWith('b')); // Output: 3
print('Last index of string starting with \'b\': $lastIndex');
}
Last index of string starting with 'b': 3
In this Dart tutorial, we learned about lastIndexWhere() method of List: the syntax and few working examples with output and detailed explanation for each example.