prefer-conditional-expressions
Recommends using a conditional expression instead of assigning to the same variable or returning a value in each branch of an if statement.
⚙️ Config
Set ignore-nested
(default is false
) to ignore cases with multiple nested conditional expressions (example).
analysis_options.yaml
dart_code_metrics:
rules:
- prefer-conditional-expressions:
ignore-nested: false
Example
❌ Bad:
int a = 0;
// LINT: Prefer rewriting this 'if' statement into a conditional expression.
if (a > 0) {
a = 1;
} else {
a = 2;
}
// LINT: Prefer rewriting this 'if' statement into a conditional expression.
if (a > 0) a = 1;
else a = 2;
int function() {
// LINT: Prefer rewriting this 'if' statement into a conditional expression.
if (a == 1) {
return 0;
} else {
return 1;
}
// LINT: Prefer rewriting this 'if' statement into a conditional expression.
if (a == 2) return 0;
else return 1;
}
✅ Good:
int a = 0;
a = a > 0 ? 1 : 2;
int function() {
return a == 2 ? 0 : 1;
}
Example with "ignore-nested"
Config
analysis_options.yaml
dart_code_metrics:
rules:
- prefer-conditional-expressions:
ignore-nested: true
✅ Good:
if (condition) { // Correct, uses a conditional expression inside
value = !another ? 'new' : 'old';
} else {
value = null;
}