Dart List indexWhere()
Syntax & Examples


Syntax of List.indexWhere()

The syntax of List.indexWhere() method is:

 int indexWhere(bool test(E element), [int start = 0]) 

This indexWhere() method of List the first index in the list that satisfies the provided test.

Parameters

ParameterOptional/RequiredDescription
testrequireda function that returns true for the desired element
startoptional [default value is 0]the index at which to start searching

Return Type

List.indexWhere() returns value of type int.



✐ Examples

1 Find index of first element > 2 in a list of numbers

In this example,

  1. We create a list numbers containing integers 1 to 5.
  2. We use indexWhere() with a test function that returns true for elements > 2.
  3. The first index where the test function returns true is printed.

Dart Program

void main() {
  var numbers = [1, 2, 3, 4, 5];
  var index = numbers.indexWhere((element) => element > 2);
  print('Index of first element > 2: $index');
}

Output

Index of first element > 2: 2

2 Find index of first occurrence of 'd' in a list of characters

In this example,

  1. We create a list characters containing characters 'a' to 'e'.
  2. We use indexWhere() with a test function that returns true for elements equal to 'd'.
  3. The first index where the test function returns true is printed.

Dart Program

void main() {
  var characters = ['a', 'b', 'c', 'd', 'e'];
  var index = characters.indexWhere((element) => element == 'd');
  print('Index of first element == \'d\': $index');
}

Output

Index of first element == 'd': 3

3 Find index of first element with length > 5 in a list of strings

In this example,

  1. We create a list words containing strings 'apple' to 'eggplant'.
  2. We use indexWhere() with a test function that returns true for elements with length > 5.
  3. The first index where the test function returns true is printed.

Dart Program

void main() {
  var words = ['apple', 'banana', 'cherry', 'date', 'eggplant'];
  var index = words.indexWhere((element) => element.length > 5);
  print('Index of first element with length > 5: $index');
}

Output

Index of first element with length > 5: 4

Summary

In this Dart tutorial, we learned about indexWhere() method of List: the syntax and few working examples with output and detailed explanation for each example.