The syntax of List.indexOf() method is:
int indexOf(E element, [int start = 0])
This indexOf() method of List the first index of element
in this list.
Parameter | Optional/Required | Description |
---|---|---|
element | required | the element to search for within the list |
start | optional [default value is 0] | the index to start searching from within the list |
List.indexOf() returns value of type int
.
In this example,
numbers
containing the numbers 1, 2, 3, 4, 5
.indexOf()
method to find the index of the number 3
in the list.3
is printed to standard output.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
int index = numbers.indexOf(3); // Output: 2
print('Index of 3: $index');
}
Index of 3: 2
In this example,
characters
containing the characters 'a', 'b', 'c', 'd', 'e'
.indexOf()
method to find the index of the character 'c'
in the list.'c'
is printed to standard output.void main() {
List<String> characters = ['a', 'b', 'c', 'd', 'e'];
int index = characters.indexOf('c'); // Output: 2
print('Index of c: $index');
}
Index of c: 2
In this example,
strings
containing the strings 'apple', 'banana', 'cherry'
.indexOf()
method to find the index of the string 'banana'
in the list.'banana'
is printed to standard output.void main() {
List<String> strings = ['apple', 'banana', 'cherry'];
int index = strings.indexOf('banana'); // Output: 1
print('Index of banana: $index');
}
Index of banana: 1
In this Dart tutorial, we learned about indexOf() method of List: the syntax and few working examples with output and detailed explanation for each example.