Skip to content

avoid_negated_conditions

v1.0.0WarningFixConfigurableControl Flow

This rule flags an if/else or a conditional expression whose condition is negated, so the else branch is the positive case.

When the condition is negated and there is an else, the reader has to hold a negation just to know what the second branch is for. Swapping the branches lets each one state its case directly.

The rule only fires where the swap is a genuine improvement:

  • Only with an else. A bare if (!x) return; is a guard, the clearest form there is — and prefer_early_return actively asks for it, so reporting it here would set the two rules fighting.
  • Never on an else if chain. That encodes an ordered sequence of tests; swapping the first pair would reorder the whole chain.
  • Never on != null or != 0. x != null is the null check the language is built around, and byPoints != 0 ? byPoints : ... is the comparator tie-break idiom. Both state a positive fact, and both turned up as false positives on a production codebase.
  • Never for a pattern if. The swapped branch could not see the bound variables.

This rule is in the pedantic preset: branch ordering is a house style.

if (!user.isActive) {
showInactiveBanner();
} else {
showDashboard();
}
final label = !isReady ? 'Waiting' : 'Ready';
if (user.isActive) {
showDashboard();
} else {
showInactiveBanner();
}
final label = isReady ? 'Ready' : 'Waiting';
// Still fine: a guard has no else to swap with.
if (!user.isActive) return;
// Still fine: `!= null` states a positive fact.
if (token != null) {
use(token);
} else {
requestToken();
}

This rule is in the pedantic preset, so it is enabled by preset: pedantic or by name:

many_lints.yaml
rules:
avoid_negated_conditions:
enabled: true
analysis_options.yaml
many_lints:
rules:
avoid_negated_conditions:
report_not_equal: false
Option Type Default Description
report_not_equal bool true Whether != counts as a negation. != null and != 0 are never reported either way

To disable this rule:

many_lints.yaml
rules:
avoid_negated_conditions: false

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