The lastIndexOf()
method of the list class finds the index of the last occurrence of a given element in a list.
list_name.lastIndexOf(value, [int? start]);
Note: list_name is the name of the list object.
value
: The element we want to find.start
: Represents the index with which to begin the search.Note: If
start
is not provided, thelastIndexOf()
method searches from the end of the list.
The method lastIndexOf()
returns the index of the last occurrence of the given element in the list. Otherwise, it returns -1
.
The following code shows how to use the lastIndexOf()
method in Dart:
void main() {// Creating a listvar myList = [20, 15, 50, 50, 60, 50, 20];// Item to be foundint searchItem = 50;// using the lastIndexOf() with the start parameter// display resultprint(myList.lastIndexOf(searchItem, 3));// using the lastIndexOf() without the start paramater// display resultprint(myList.lastIndexOf(searchItem));// Item to be foundsearchItem = 10;int found = myList.lastIndexOf(searchItem);// if search item is not present in the list,// it returns -1if (found != -1) {print("$searchItem is found at index $found");}else {print("$searchItem is not present in the list");}var string = 'There are four apples in the basket';// item to be foundfound = string.lastIndexOf('a');print('The character a is found at index ${found}');}
The code above generates the following output:
3
: the index of the last occurrence of the number 50
in the given list starting from index 3
.5
: the index of the last occurrence of the number 50
in the given list starting from index 0
.10
could not be found in the given list.30
: The index of the last occurrence of the character a
in the given string starting from index 0
.