singleWhere method

E singleWhere (bool test(E element), { E orElse() })

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. Otherwise, if there are no matching elements, or if there is more than one matching element, the result of invoking the orElse function is returned. If orElse is omitted, it defaults to throwing a StateError.


E singleWhere(bool test(E element), {E orElse()}) {
  int length = this.length;
  E match = null;
  bool matchFound = false;
  for (int i = 0; i < length; i++) {
    E element = elementAt(i);
    if (test(element)) {
      if (matchFound) {
        throw IterableElementError.tooMany();
      matchFound = true;
      match = element;
    if (length != this.length) {
      throw new ConcurrentModificationError(this);
  if (matchFound) return match;
  if (orElse != null) return orElse();
  throw IterableElementError.noElement();