The method indexOf()
finds the index of the first occurrence of an element in the list with the same value as the given element.
list_name.indexOf(value);
value
: represents the element whose index is to be foundThe method indexOf()
returns the index of the first occurrence of the element in the list if found. Otherwise, it returns -1.
The following code shows how to use the indexOf()
method in Dart:
void main(){// Creating listvar myList = [20, 15, 37, 23, 60, 50, 20];// Item to be foundint searchItem = 37;// Stores the index in variable foundint 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.