How can you return null from orElse within Iterable.firstWhere with null-safety enabled?

A handy function, firstWhereOrNull, solves this exact problem.

Import package:collection which includes extension methods on Iterable.

import 'package:collection/collection.dart';

final list = [1, 2, 3];
final x = list.firstWhereOrNull((element) => element > 3);

if (x == null) {
  // do stuff...
}

Leave a Comment