avoid_unused_after_null_check
v1.0.0 Warning Control Flow
This rule is in the pedantic preset.
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.
Why use this rule
Section titled “Why use this rule”A null check is a statement of intent: this branch is safe because x is non-null here. When the branch then uses a different variable, the guard protects nothing and the code reads as though it does.
The common shape is a copy-paste slip — two similarly named variables, one checked and the other used. Nothing in the type system objects, because the variable actually used may be perfectly non-null on its own. The result is a check that looks like safety and provides none.
See also: Dart: understanding null safety
if (user != null) { print(fallbackUser.name); // `user` was checked, `fallbackUser` is used}The inverted form has the same problem:
if (user == null) { return;} else { print(fallbackUser.name); // the else branch is the guarded one}if (user != null) { print(user.name);}Known limitations
Section titled “Known limitations”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.
Configuration
Section titled “Configuration”This rule appears only in the pedantic preset because checking whether a
value exists can legitimately select behavior without reading the value inside
the selected branch.
Enable it by name:
rules: avoid_unused_after_null_check: trueTo keep the rule on but skip certain paths, use per-rule exclude.
Related rules
Section titled “Related rules”avoid_cascade_after_if_null— Detect cascades after if-null operators without parentheses.prefer_simpler_patterns_null_check— Suggest simpler null-check patterns in if-case expressions.avoid_collapsible_if— Merge nested if statements with &&.avoid_constant_conditions— Detect comparisons where both sides are constants.