Dart List lastIndexOf()
Syntax & Examples
Syntax of List.lastIndexOf()
The syntax of List.lastIndexOf() method is:
int lastIndexOf(E element, [int? start])
This lastIndexOf() method of List the last index of element
in this list.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
element | required | the element to find the last index of in the list |
start | optional | if provided, the search will start from this index backwards |
Return Type
List.lastIndexOf() returns value of type int
.
✐ Examples
1 Find the last index of an element in a list of numbers
In this example,
- We create a list named
numbers
with elements [1, 2, 3, 4, 3, 2, 1]. - We then use the
lastIndexOf()
method to find the last index of the element 3 innumbers
. - The last index of 3 is printed to standard output.
Dart Program
void main() {
List<int> numbers = [1, 2, 3, 4, 3, 2, 1];
int lastIndex = numbers.lastIndexOf(3);
print('Last index of 3: $lastIndex');
}
Output
Last index of 3: 4
2 Find the last index of an element in a list of characters
In this example,
- We create a list named
characters
with elements ['a', 'b', 'c', 'd', 'c']. - We then use the
lastIndexOf()
method to find the last index of the element 'c' incharacters
. - The last index of 'c' is printed to standard output.
Dart Program
void main() {
List<String> characters = ['a', 'b', 'c', 'd', 'c'];
int lastIndex = characters.lastIndexOf('c');
print('Last index of "c": $lastIndex');
}
Output
Last index of "c": 4
3 Find the last index of an element in a list of strings
In this example,
- We create a list named
words
with elements ['apple', 'banana', 'cherry', 'apple']. - We then use the
lastIndexOf()
method to find the last index of the element 'apple' inwords
. - The last index of 'apple' is printed to standard output.
Dart Program
void main() {
List<String> words = ['apple', 'banana', 'cherry', 'apple'];
int lastIndex = words.lastIndexOf('apple');
print('Last index of "apple": $lastIndex');
}
Output
Last index of "apple": 3
Summary
In this Dart tutorial, we learned about lastIndexOf() method of List: the syntax and few working examples with output and detailed explanation for each example.