To find the index of a specified element in a list in Dart, you can use the indexOf
method of the List class.
In this example,
myList
with some elements.indexOf
method to find the index of the specified element in the list.indexOf
method returns the index of the first occurrence of the element in the list, or -1 if the element is not found.void main() {
List<int> myList = [10, 20, 30, 40, 50];
int searchElement = 40;
int index = myList.indexOf(searchElement);
if (index != -1) {
print('Index of element is: \$index');
} else {
print('Element not found');
}
}
Index of element is: 3
In this example,
myList
with some string elements.indexOf
method to find the index of the specified string in the list.indexOf
method returns the index of the first occurrence of the string in the list, or -1 if the string is not found.void main() {
List<String> myList = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
String searchElement = 'cherry';
int index = myList.indexOf(searchElement);
if (index != -1) {
print('Index of element is: \$index');
} else {
print('Element not found');
}
}
Index of element is: 2
In this tutorial, we learned How to get the Index of Specified Element in a List in Dart language with well detailed examples.