singleWhere method
Returns an Optional
containing the only element that satisfies the given
predicate
if there is exactly one, otherwise returns Optional.empty
.
Checks elements to see if predicate(element)
returns true
.
If exactly one element satisfies predicate
, that element is returned
wrapped in an Optional
.
If none or more than one matching element is found, an Optional.empty
is
returned.
If the null
value satisfies the given predicate
, this lookup can not
distinguish between not having exactly one element satisfying the
predicate and only containing the null
value satisfying the predicate.
Methods like contains can be used if the distinction is important.
Implementation
Optional<T> singleWhere(bool Function(T value) predicate) {
try {
return Optional.ofNullable(_set.singleWhere(predicate));
// ignore: avoid_catching_errors
} on Error {
return const Optional.empty();
}
}