avoid-cascade-after-if-null
preset: recommended
Warns when a cascade expression is used after if null (??) binary expression without parentheses.
Not adding parentheses may lead to unexpected results since the cascade will be executed after if null expression.
Example
❌ Bad:
class Cow {
void moo() {}
}
class Ranch {
final Cow? _cow;
Ranch([Cow? cow])
// LINT: Cascade expressions without parentheses placed after ?? can lead to unexpected errors. Try adding parentheses to ensure correct precedence.
: _cow = cow ?? Cow()
..moo();
}
void main() {
final Cow? nullableCow;
// LINT: Cascade expressions without parentheses placed after ?? can lead to unexpected errors. Try adding parentheses to ensure correct precedence.
final cow = nullableCow ?? Cow()
..moo();
}
✅ Good:
void main() {
final Cow? nullableCow;
final cow = (nullableCow ?? Cow())..moo(); // Correct, parentheses are used before cascade
final cow = nullableCow ?? (Cow()..moo()); // Correct, cascade is called only for the new instance
}