firstWhereIndexedOrNull method

T? firstWhereIndexedOrNull(
  1. bool test(
    1. int index,
    2. T element
    )
)

Finds the first element that satisfies the test condition.

This method is similar to firstWhere but:

  • Provides access to both the element and its index in the test function
  • Returns null instead of throwing an exception when no match is found
  • Is safer for cases where you're not sure if a match exists

Parameters:

  • test: Function that takes an index and element, returns true if the element matches

Returns:

  • The first matching element, or null if no match is found

Example:

final list = ['a', 'b', 'c', 'd'];
final result = list.firstWhereIndexedOrNull((index, element) =>
  index > 1 && element == 'c'
);
// Result: 'c' (found at index 2)

Implementation

T? firstWhereIndexedOrNull(bool Function(int index, T element) test) {
  var index = 0;
  for (var element in this) {
    if (test(index++, element)) return element;
  }
  return null;
}