singleWhereOrNull method Null safety

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

The single element satisfying test.

Returns null if there are either no elements or more than one element satisfying test.

Notice: This behavior differs from Iterable.singleWhere which always throws if there are more than one match, and only calls the orElse function on zero matches.

Implementation

T? singleWhereOrNull(bool Function(T element) test) {
  T? result;
  var found = false;
  for (var element in this) {
    if (test(element)) {
      if (!found) {
        result = element;
        found = true;
      } else {
        return null;
      }
    }
  }
  return result;
}