null_ closures
Details about the 'null_closures' diagnostic produced by the Dart analyzer.
Don't pass 'null' as an argument where a closure is expected.
Description
#
The analyzer produces this diagnostic when the literal null
is passed as the argument for a parameter that expects a closure,
in an invocation of certain functions, constructors, and methods
in the dart:async, dart:collection, and dart:core
libraries.
Examples include the orElse parameter of Iterable.firstWhere
and
the cleanUp parameter of Future.wait.
When the parameter is nullable, its default value is typically null,
so passing null explicitly has the same effect as omitting the argument.
Example
#
The following code produces this diagnostic because
null is passed as the argument for the orElse parameter:
int f(List<int> list) {
return list.firstWhere((e) => e.isEven, orElse: null);
}
Common fixes
#
If you want the default behavior, then remove the argument.
For Iterable.firstWhere, the default is to
throw a StateError when no element matches:
int f(List<int> list) {
return list.firstWhere((e) => e.isEven);
}
If you need a fallback value, then pass a closure that returns it:
int f(List<int> list) {
return list.firstWhere((e) => e.isEven, orElse: () => 0);
}
Unless stated otherwise, the documentation on this site reflects Dart 3.14. Report an issue.