singleOrNull method

T? singleOrNull(
  1. bool test(
    1. T? element
    )
)

Filters this iterable with all elements that satisfy the predicate test. Throws a StateError if the filtered iterable contains more than one element. Otherwise returns the only remaining element or null.

Implementation

T? singleOrNull(bool Function(T? element) test) {
  final results = where(test);

  if (results.isEmpty) {
    return null;
  }

  if (results.length > 1) {
    throw StateError('More than one item found.');
  }

  return results.first;
}