avoid_negated_conditions
v1.0.0WarningFixConfigurableControl Flow
many_lints.yaml
analysis_options.yaml many_lints.yaml
many_lints.yaml
This rule flags an if/else or a conditional expression whose condition is negated, so the else branch is the positive case.
Why use this rule
Section titled “Why use this rule”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 bareif (!x) return;is a guard, the clearest form there is — andprefer_early_returnactively asks for it, so reporting it here would set the two rules fighting. - Never on an
else ifchain. That encodes an ordered sequence of tests; swapping the first pair would reorder the whole chain. - Never on
!= nullor!= 0.x != nullis the null check the language is built around, andbyPoints != 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();}Enabling this rule
Section titled “Enabling this rule”This rule is in the pedantic preset, so it is enabled by preset: pedantic or by name:
rules: avoid_negated_conditions: enabled: trueOptions
Section titled “Options”many_lints: rules: avoid_negated_conditions: report_not_equal: falserules: 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 |
Turning this rule off
Section titled “Turning this rule off”To disable this rule:
rules: avoid_negated_conditions: falseTo keep the rule on but skip certain paths, use per-rule exclude.
Related rules
Section titled “Related rules”avoid_inverted_boolean_checks— Use the opposite operator instead of negating a comparison.avoid_unnecessary_negations— Collapse double negations.prefer_returning_condition— Return the condition instead of true/false branches.avoid_constant_conditions— Detect comparisons where both sides are constants.