Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

flutter

dart

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?

like image 532
Alex Hartford Avatar asked Jun 04 '21 19:06

Alex Hartford


People also ask

How do you return a NULL in darts?

Dart allows returning null in functions with void return type but it also allow using return; without specifying any value. To have a consistent way you should not return null and only use an empty return.

Can use the default list constructor when null safety is enabled?

The default 'List' constructor isn't available when null safety is enabled.


2 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...
}
like image 190
Alex Hartford Avatar answered Oct 13 '22 00:10

Alex Hartford


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;
}
like image 1
Vishal Singh Avatar answered Oct 12 '22 22:10

Vishal Singh