What is List indexOf() method in Dart?

The method indexOf() finds the index of the first occurrence of an element in the list with the same value as the given element.

Syntax

list_name.indexOf(value);

Parameter

  • value: represents the element whose index is to be found

Return value

The method indexOf() returns the index of the first occurrence of the element in the list if found. Otherwise, it returns -1.

Code

The following code shows how to use the indexOf() method in Dart:

void main(){
// Creating list
var myList = [20, 15, 37, 23, 60, 50, 20];
// Item to be found
int searchItem = 37;
// Stores the index in variable found
int found = myList.indexOf(searchItem);
if (found != -1) {
print("$searchItem is found at index $found");
} else {
print("$searchItem is not present in the list");
}
}

Note: The method indexOf() returns -1 if the item is not found in the list.

Free Resources