avoid-negated-conditions
Warns when an if statement or conditional expression have a negated condition that can be inverted.
⚙️ Config
Set ignore-null-checks
(default is false
) to exclude null checks (example).
analysis_options.yaml
dart_code_metrics:
rules:
- avoid-negated-conditions:
ignore-null-checks: false
Example
❌ Bad:
// LINT: Avoid negated conditions. Try removing the negation and swapping the branches.
if (!flag) {
...
} else {
...
}
// LINT: Avoid negated conditions. Try removing the negation and swapping the branches.
if (flag is! bool) {
...
} else {
...
}
// LINT: Avoid negated conditions. Try removing the negation and swapping the branches.
final newValue = !flag ? value - 1 : value + 1;
✅ Good:
if (flag) { // Correct, no negated condition
...
} else {
...
}
if (flag is bool) {
...
} else {
...
}
final newValue = flag ? value + 1 : value - 1;
Example with "ignore-null-checks"
Config
analysis_options.yaml
dart_code_metrics:
rules:
- avoid-negated-conditions:
ignore-null-checks: false
✅ Good:
int? value = 1;
void fn() {
if (value != null) { // Correct, null checks are ignored
} else {}
if (value == null) {
} else {}
}