Dart List lastIndexWhere()
Syntax & Examples
Syntax of List.lastIndexWhere()
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
.
Parameters
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 |
Return Type
List.lastIndexWhere() returns value of type int
.
✐ Examples
1 Find the last index of an even number in the list
In this example,
- We create a list named
numbers
containing the numbers[1, 2, 3, 4, 5]
. - We then use the
lastIndexWhere()
method with a test function that checks if the element is even. - The method returns the last index of the even number in the list.
- We print the result to standard output.
Dart Program
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');
}
Output
Last index of even number: 3
2 Find the last index of the character 'c' in the list
In this example,
- We create a list named
characters
containing the characters['a', 'b', 'c', 'd', 'e']
. - We then use the
lastIndexWhere()
method with a test function that checks if the element is equal to 'c'. - The method returns the last index of the character 'c' in the list.
- We print the result to standard output.
Dart Program
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');
}
Output
Last index of character 'c': 2
3 Find the last index of a string starting with 'b' in the list
In this example,
- We create a list named
strings
containing the strings['apple', 'banana', 'cherry', 'banana']
. - We then use the
lastIndexWhere()
method with a test function that checks if the element starts with 'b'. - The method returns the last index of the string starting with 'b' in the list.
- We print the result to standard output.
Dart Program
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');
}
Output
Last index of string starting with 'b': 3
Summary
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.