# singleWhere method

1. @override

E singleWhere(

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

})
override

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.

Example:

    final numbers = <int>[2, 2, 10];
    var result = numbers.singleWhere((element) => element > 5); // 10

When no matching element is found, the result of calling `orElse` is returned instead.

    result = numbers.singleWhere((element) => element == 1,
        orElse: () => -1); // -1

There must not be more than one matching element.

    result = numbers.singleWhere((element) => element == 2); // Throws Error.

## Implementation

    @override
    E singleWhere(bool Function(E element) test, {E Function()? orElse}) {
      E? result;
      bool found = false;
      for (final element in this) {
        if (test(element)) {
          if (found) {
            throw IllegalStateException('More than one element satisfies the predicate.');
          }
          result = element;
          found = true;
        }
      }
      if (found) {
        return result as E;
      }
      if (orElse != null) {
        return orElse();
      }
      throw IllegalStateException('No element satisfies the predicate.');
    }