sole<T> static method

T sole<T>(
  1. Iterable<T> list, {
  2. bool predicate(
    1. T
    )?,
})

Returns the single element matching predicate. Throws if zero or more than one element matches.

Implementation

static T sole<T>(Iterable<T> list, {bool Function(T)? predicate}) {
  final filtered = predicate == null
      ? list.toList()
      : list.where(predicate).toList();
  if (filtered.isEmpty) {
    throw StateError('sole: no items found');
  }
  if (filtered.length > 1) {
    throw StateError('sole: expected 1 item, found ${filtered.length}');
  }
  return filtered.first;
}