prefer_ null_ aware_ method_ calls
Details about the 'prefer_null_aware_method_calls' diagnostic produced by the Dart analyzer.
Use a null-aware invocation of the 'call' method rather than explicitly testing for 'null'.
Description
#
The analyzer produces this diagnostic when
a comparison with null (using the != operator) is used to
guard the invocation of a nullable function,
and the function is invoked using the not-null assertion operator (!).
The diagnostic is only reported when the comparison is the condition of either:
-
An
ifstatement that doesn't have anelseclause and whose body contains only the invocation. -
A conditional expression (using the
?:operator) whose then expression is the invocation and whose else expression isnull.
Examples
#
The following code produces this diagnostic because
the function f uses an if statement to check
that the top-level variable g isn't null before invoking it
using the not-null assertion operator (!):
void Function()? g;
void f() {
if (g != null) {
g!();
}
}
The following code produces this diagnostic because
the function f uses a conditional expression to check
that the top-level variable g isn't null before invoking it
using the not-null assertion operator (!):
int Function()? g;
int? f() => g != null ? g!() : null;
Common fixes
#
If the invocation is guarded by an if statement,
then replace the if statement with
a null-aware invocation of the call method:
void Function()? g;
void f() {
g?.call();
}
If the invocation is guarded by a conditional expression,
then replace the conditional expression with
a null-aware invocation of the call method:
int Function()? g;
int? f() => g?.call();
Unless stated otherwise, the documentation on this site reflects Dart 3.14. Report an issue.