Skip to content

avoid_cascade_after_if_null

v0.3.0 Warning Control Flow

Warns when a cascade expression (..) follows an if-null (??) operator without parentheses. Due to operator precedence, it is ambiguous whether the cascade applies to the right-hand side of ?? or to the entire expression, which can produce unexpected results.

Dart’s cascade operator and if-null operator have surprising precedence interactions. Without parentheses, a ?? B()..method() is parsed as a ?? (B()..method()), which may not be what the developer intended. Adding explicit parentheses makes the intent clear and prevents subtle bugs.

See also: Cascade notation

void bad(Cow? nullableCow) {
// Unclear whether ..moo() applies to the result of ?? or just Cow()
final cow = nullableCow ?? Cow()
..moo();
// Multiple cascades after if-null
final cow2 = nullableCow ?? Cow()
..moo()
..age = 5;
}
void good(Cow? nullableCow) {
// Cascade applies to the entire if-null expression
final cow = (nullableCow ?? Cow())..moo();
// Cascade applies only to the new instance
final cow2 = nullableCow ?? (Cow()..moo());
// No if-null involved, cascade is unambiguous
final cow3 = Cow()..moo();
}

To disable this rule:

plugins:
many_lints:
diagnostics:
avoid_cascade_after_if_null: false