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

Viewed 5497

Prior to null-safe dart, the following was valid syntax:

final list = [1, 2, 3];
final x = list.firstWhere((element) => element > 3, orElse: () => null);

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

Now, firstWhere requires orElse to return an int, opposed to an int?, therefore I cannot return null.

How can I return null from orElse?

3 Answers

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...
}

You don't need external package for this instead you can use try/catch

int? x;
try {
  x = list.firstWhere((element) => element > 3);
} catch(e) {
  x = null;
}

A little bit late but i came up with this:


typedef FirstWhereClosure = bool Function(dynamic);

extension FirstWhere on List {
  dynamic frstWhere(FirstWhereClosure closure) {
    int index = this.indexWhere(closure);

    if (index != -1) {
      return this[index];
    }
    return null;
  }
}

Example use:

class Test{
  String name;
  int code;
  
  Test(code, this.name);
}

Test? test = list.frstWhere(t)=> t.code==123);
Related