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) {
switch (size) {
case 0:
throw const NoSuchElementException("List is empty");
case 1:
return get(0);
default:
throw ArgumentError("List has more than one element.");
}
} 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!;
}
}