single method
Returns the single element matching the given predicate
, or throws an exception if the list is empty or has more than one element.
Implementation
T single([bool Function(T)? predicate]) {
if (predicate == null) {
final i = iterator();
if (!i.hasNext()) {
throw const NoSuchElementException("Collection is empty.");
}
final single = i.next();
if (i.hasNext()) {
throw ArgumentError("Collection has more than one element.");
}
return single;
} else {
T? single;
var found = false;
for (final element in iter) {
if (predicate(element)) {
if (found) {
throw ArgumentError(
"Collection contains more than one matching element.");
}
single = element;
found = true;
}
}
if (!found) {
throw const NoSuchElementException(
"Collection contains no element matching the predicate.");
}
return single!;
}
}