firstWhereOrNull method

E? firstWhereOrNull(
  1. bool test(
    1. E
    )
)

The first element satisfying test, or null if none match.

A null-safe alternative to Iterable.firstWhere that returns null instead of throwing StateError when no element matches.

final vehicle = vehicles.firstWhereOrNull((v) => v.vrn == 'ABC123');
final diesel = vehicles.firstWhereOrNull((v) => v.fuelType == 'Diesel');

Implementation

E? firstWhereOrNull(bool Function(E) test) => cast<E?>().firstWhere((E? v) => v != null && test(v), orElse: () => null);