null_ closures
Learn about the null_closures linter rule.
Do not pass null as an argument where a closure
is expected.
Details
#
DON'T pass null as an argument
where a closure is expected.
Often a closure that is passed to a method will only be called
conditionally, so that tests and "happy path" production calls
do not reveal that null
will result in an exception being thrown.
This rule only catches null literals being passed where closures are expected in the following locations:
Constructors
#-
From
dart:async-
Futureat the 0th positional parameter -
Future.microtaskat the 0th positional parameter -
Future.syncat the 0th positional parameter -
Timerat the 0th positional parameter -
Timer.periodicat the 1st positional parameter
-
-
From
dart:core-
List.generateat the 1st positional parameter
-
Static functions
#-
From
dart:async-
scheduleMicrotaskat the 0th positional parameter -
Future.doWhileat the 0th positional parameter -
Future.forEachat the 0th positional parameter -
Future.waitat the named parametercleanup -
Timer.runat the 0th positional parameter
-
Instance methods
#-
From
dart:async-
Future.thenat the 0th positional parameter -
Future.completeat the 0th positional parameter
-
-
From
dart:collection-
Queue.removeWhereat the 0th positional parameter - `Queue.retain
-
Iterable.firstWhereat the 0th positional parameter, and the named parameterorElse -
Iterable.forEachat the 0th positional parameter -
Iterable.foldat the 1st positional parameter -
Iterable.lastWhereat the 0th positional parameter, and the named parameterorElse -
Iterable.mapat the 0th positional parameter -
Iterable.reduceat the 0th positional parameter -
Iterable.singleWhereat the 0th positional parameter, and the named parameterorElse -
Iterable.skipWhileat the 0th positional parameter -
Iterable.takeWhileat the 0th positional parameter -
Iterable.whereat the 0th positional parameter -
List.removeWhereat the 0th positional parameter -
List.retainWhereat the 0th positional parameter -
String.replaceAllMappedat the 1st positional parameter -
String.replaceFirstMappedat the 1st positional parameter -
String.splitMapJoinat the named parametersonMatchandonNonMatch
-
BAD:
[1, 3, 5].firstWhere((e) => e.isOdd, orElse: null);
GOOD:
[1, 3, 5].firstWhere((e) => e.isOdd, orElse: () => null);
Enable
#
To enable the null_closures rule, add
null_closures under
linter > rules in your
analysis_options.yaml
file:
linter:
rules:
- null_closures
If you're instead using the YAML map syntax to configure
linter rules, add null_closures: true under
linter > rules:
linter:
rules:
null_closures: true
除非另有说明,文档之所提及适用于 Dart 3.12.2 版本报告页面问题.