Dart: The Iterable.firstWhere method no longer accepts orElse: () => null.
https://dart.dev/null-safety/faq#the-iterablefirstwhere-method-no-longer-accepts-orelse---null
と、FAQにも書いてありますが、
こっちはもちろんエラーになる
void main(List<String> args) { final list = [1, 2, 3]; // The return type 'Null' isn't a 'int', as required by the closure's context. final x = list.firstWhere((element) => element > 3, orElse: () => null); if (x == null) { // do stuff... } }
こっちは正常に実行できる
void main(List<String> args) { final List<int?> list = [1, 2, 3]; // 本当にlistにnullが混ざるなら、element!だとだめですが。。。 final x = list.firstWhere((element) => element! > 3, orElse: () => null); assert(x == null); }
後者のパターンも疑問が残る使い方ではあるので、 大人しくpackage:collectionを使うのがいいとは思います。
もしくは
void main(List<String> args) { final List<int> list = [1, 2, 3]; final found = list.where((element) => element > 3); final x = found.isEmpty ? null : found.first; assert(x == null); }
こんな感じかなと思います。