find method

E? find(
  1. bool test(
    1. E element
    ), {
  2. E orElse()?,
})

find the first element that satisfies the given predicate test.

Iterates through elements and returns the first to satisfy test.

Example:

final numbers = <int>[1, 2, 3, 5, 6, 7];
var result = numbers.firstWhere((element) => element < 5); // 1
result = numbers.find((element) => element > 5); // 6
result = numbers.find((element) => element > 10); // null
result =
    numbers.find((element) => element > 10, orElse: () => -1); // -1

If no element satisfies test, the result of invoking the orElse function is returned. If orElse is omitted, it defaults to return a null. Stops iterating on the first matching element.

Implementation

E? find(bool Function(E element) test, {E Function()? orElse}) {
  for (E element in this) {
    if (test(element)) return element;
  }
  if (orElse != null) return orElse();
  return null;
}