lastWhereIndexed method

E lastWhereIndexed(
  1. bool test(
    1. int index,
    2. E element
    ), {
  2. E orElse()?,
})

Returns the last element that satisfies the given test function along with its index in the iterable.

If no element satisfies the condition, and orElse is not provided, it throws a StateError.

Example:

[1, 2, 3, 4, 5].lastWhereIndexed((index, element) => element % 2 == 0); // 4

Implementation

E lastWhereIndexed(
  bool Function(int index, E element) test, {
  E Function()? orElse,
}) {
  E? result;
  int index = 0;
  for (final element in this) {
    if (test(index++, element)) result = element;
  }
  if (result != null) return result;
  if (orElse != null) return orElse();
  throw StateError("No element");
}