Dart List indexOf()
Syntax & Examples


Syntax of List.indexOf()

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.

Parameters

ParameterOptional/RequiredDescription
elementrequiredthe element to search for within the list
startoptional [default value is 0]the index to start searching from within the list

Return Type

List.indexOf() returns value of type int.



✐ Examples

1 Find the index of number 3

In this example,

  1. We create a list named numbers containing the numbers 1, 2, 3, 4, 5.
  2. We then use the indexOf() method to find the index of the number 3 in the list.
  3. The index of 3 is printed to standard output.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3, 4, 5];
  int index = numbers.indexOf(3); // Output: 2
  print('Index of 3: $index');
}

Output

Index of 3: 2

2 Find the index of character 'c'

In this example,

  1. We create a list named characters containing the characters 'a', 'b', 'c', 'd', 'e'.
  2. We then use the indexOf() method to find the index of the character 'c' in the list.
  3. The index of 'c' is printed to standard output.

Dart Program

void main() {
  List<String> characters = ['a', 'b', 'c', 'd', 'e'];
  int index = characters.indexOf('c'); // Output: 2
  print('Index of c: $index');
}

Output

Index of c: 2

3 Find the index of string 'banana'

In this example,

  1. We create a list named strings containing the strings 'apple', 'banana', 'cherry'.
  2. We then use the indexOf() method to find the index of the string 'banana' in the list.
  3. The index of 'banana' is printed to standard output.

Dart Program

void main() {
  List<String> strings = ['apple', 'banana', 'cherry'];
  int index = strings.indexOf('banana'); // Output: 1
  print('Index of banana: $index');
}

Output

Index of banana: 1

Summary

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.