singleWhere method

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

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}) {
  int length = this.length;
  late E match;
  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();
}

© 2012 the Dart project authors
Licensed under the Creative Commons Attribution-ShareAlike License v4.0.
https://api.dart.dev/stable/2.13.0/dart-collection/ListQueue/singleWhere.html