singleOrNull method

T? singleOrNull([
  1. bool predicate(
    1. T
    )?
])

Returns the single element matching the given predicate, or null if element was not found or more than one element was found.

Implementation

T? singleOrNull([bool Function(T)? predicate]) {
  if (predicate == null) {
    final i = iterator();
    if (!i.hasNext()) return null;
    final single = i.next();
    if (i.hasNext()) {
      return null;
    }
    return single;
  } else {
    T? single;
    var found = false;
    for (final element in iter) {
      if (predicate(element)) {
        if (found) return null;
        single = element;
        found = true;
      }
    }
    if (!found) return null;
    return single;
  }
}