Skip to content

avoid_unused_after_null_check

v1.0.0 Warning Control Flow

This rule flags if (x != null) { ... } where the guarded branch never mentions x. The check exists to make x usable, so a branch that ignores it is usually operating on the wrong variable — a copy-paste slip between two similarly named values. Nothing in the type system objects, because the variable actually used may be perfectly non-null on its own.

See also: Dart: understanding null safety

name is checked, fallbackName is used:

void greet(String? name, String fallbackName) {
if (name != null) {
print(fallbackName);
}
}

The inverted form has the same problem — for x == null, the else is the guarded branch:

void greet(String? name, String fallbackName) {
if (name == null) {
print('anonymous');
} else {
print(fallbackName);
}
}
void greet(String? name, String fallbackName) {
if (name != null) {
print(name);
} else {
print(fallbackName);
}
}

Only locals and parameters are checked. A field can be read through this, passed implicitly, or mutated by any call inside the branch, so the absence of its bare name proves nothing.

The condition must be a direct comparison against null — x != null or null != x. Compound conditions, is checks, and null-aware operators are not analysed.

For x == null, only the else branch is examined, since that is the branch where the variable is known non-null. An if (x == null) with no else is not reported.

This rule is in the pedantic preset, because checking whether a value exists can legitimately select behaviour without reading the value inside the selected branch.

Enable it by name:

many_lints.yaml
rules:
avoid_unused_after_null_check: true

To keep the rule on but skip certain paths, use per-rule exclude.