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
.
Parameter | Optional/Required | Description |
---|---|---|
test | required | a function that returns true for the desired element |
start | optional [default value is 0] | the index at which to start searching |
List.indexWhere() returns value of type int
.
In this example,
numbers
containing integers 1 to 5.indexWhere()
with a test function that returns true for elements > 2.void main() {
var numbers = [1, 2, 3, 4, 5];
var index = numbers.indexWhere((element) => element > 2);
print('Index of first element > 2: $index');
}
Index of first element > 2: 2
In this example,
characters
containing characters 'a' to 'e'.indexWhere()
with a test function that returns true for elements equal to 'd'.void main() {
var characters = ['a', 'b', 'c', 'd', 'e'];
var index = characters.indexWhere((element) => element == 'd');
print('Index of first element == \'d\': $index');
}
Index of first element == 'd': 3
In this example,
words
containing strings 'apple' to 'eggplant'.indexWhere()
with a test function that returns true for elements with length > 5.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');
}
Index of first element with length > 5: 4
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.