W3cubDocs

/Dart 2

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.

Implementation

E singleWhere(bool test(E element), {E orElse()}) {
  E result = null;
  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();
}

© 2012 the Dart project authors
Licensed under the Creative Commons Attribution-ShareAlike License v4.0.
https://api.dartlang.org/stable/2.0.0/dart-collection/IterableMixin/singleWhere.html