singleWhere method Null safety

E singleWhere (
  1. bool test(
    1. E element
    ),
  2. {E orElse(
      )}
    )
    override

    Returns the single element that satisfies test.

    Checks elements to see if test(element) returns true. If exactly one element satisfies test, that element is returned. If more than one matching element is found, throws StateError. If no matching element is found, returns the result of orElse. If orElse is omitted, it defaults to throwing a StateError.

    Implementation

    E singleWhere(bool test(E element), {E Function()? orElse}) {
      late E result;
      bool foundMatching = false;
      for (E element in this) {
        if (test(element)) {
          if (foundMatching) {
            throw IterableElementError.tooMany();
          }
          result = element;
          foundMatching = true;
        }
      }
      if (foundMatching) return result;
      if (orElse != null) return orElse();
      throw IterableElementError.noElement();
    }