What is Cascade Notation?
The cascade operator .. lets you perform a sequence of operations on the same object without repeating the object name. It returns the original object, not the result of the operation.
Syntax
// Without cascade:
var paint = Paint();
paint.color = Color.blue;
paint.strokeWidth = 5.0;
paint.style = PaintingStyle.stroke;
// With cascade:
var paint = Paint()
..color = Color.blue
..strokeWidth = 5.0
..style = PaintingStyle.stroke;
Example
class QueryBuilder {
String _table = '';
List<String> _conditions = [];
int _limit = 100;
QueryBuilder from(String table) { _table = table; return this; }
QueryBuilder where(String cond) { _conditions.add(cond); return this; }
QueryBuilder limit(int n) { _limit = n; return this; }
String build() =>
'SELECT * FROM $_table WHERE $${_conditions.join(" AND ")} LIMIT $_limit';
}
void main() {
// Using cascade
var builder = QueryBuilder()
..from('users')
..where('age > 18')
..where('status = "active"')
..limit(50);
print(builder.build());
// List cascade
var list = <int>[]
..add(1)
..add(2)
..addAll([3, 4, 5])
..sort();
print(list); // [1, 2, 3, 4, 5]
}
Output:SELECT * FROM users WHERE age > 18 AND status = "active" LIMIT 50
[1, 2, 3, 4, 5]
Null-Aware Cascade
Use ?.. to cascade only if the object is not null:
List<int>? nums = null;
nums?..add(1)..add(2); // safe — does nothing if nums is null
print(nums); // null
nums = [];
nums?..add(1)..add(2);
print(nums); // [1, 2]
🧠 Quiz
1. What does the cascade operator .. return?
- A) The result of the last operation
- B) The original object ✅
- C) null
- D) A copy of the object
2. Which cascade operator is null-safe?
- A) ..
- B) ...
- C) ?..
- D) ??.. ✅ (actually ?.. is correct)
Summary
The cascade operator .. chains multiple operations on the same object in a single expression. It returns the original object, making it perfect for builder patterns and configuration. Use ?.. for null-safe cascades.