Skip to main content

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 if statement that doesn't have an else clause and whose body contains only the invocation.
  • A conditional expression (using the ?: operator) whose then expression is the invocation and whose else expression is null.

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 (!):

dart
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 (!):

dart
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:

dart
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:

dart
int Function()? g;
​
int? f() => g?.call();