What is the List.lastIndexOf() method in Dart?

Overview

The lastIndexOf() method of the list class finds the index of the last occurrence of a given element in a list.

Syntax

list_name.lastIndexOf(value, [int? start]);

Note: list_name is the name of the list object.

Parameters

  • value: The element we want to find.
  • start: Represents the index with which to begin the search.

Note: If start is not provided, the lastIndexOf() method searches from the end of the list.

Return value

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 list
var myList = [20, 15, 50, 50, 60, 50, 20];
// Item to be found
int searchItem = 50;
// using the lastIndexOf() with the start parameter
// display result
print(myList.lastIndexOf(searchItem, 3));
// using the lastIndexOf() without the start paramater
// display result
print(myList.lastIndexOf(searchItem));
// Item to be found
searchItem = 10;
int found = myList.lastIndexOf(searchItem);
// if search item is not present in the list,
// it returns -1
if (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 found
found = string.lastIndexOf('a');
print('The character a is found at index ${found}');
}

Explanation

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.
  • The number 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.

Free Resources