Dart's Cascade Notation: Chain Calls on One Object
Cascade notation (..) lets you perform a sequence of operations on the same object without repeating its name. It's ideal for configuring new instances in one block.
WHY IT EXISTS To reduce code verbosity and improve readability when initializing or configuring an object. Instead of repeating a variable name on every line to set properties or call methods, cascade notation lets you do it all in a single, chained block.
THE MENTAL MODEL Think of cascade notation (..) as giving an object a to-do list. You tell it, "Do this, then do that, then do one more thing." After all the tasks are complete, the expression gives you back the original object, not the result of the final task. This is the crucial difference from standard method chaining (.).
HOW IT WORKS You use the double-dot (..) operator to chain calls on an object. The entire expression evaluates to the object itself, not the return value of the last method. For example, myObject..doA()..doB() calls doA() and doB() on myObject, and the entire expression resolves to myObject. For nullable objects, you can use the null-aware cascade ?...
WHEN TO USE IT Use it frequently for object configuration, especially with builder patterns or when setting up UI components in Flutter. It's perfect for creating and configuring an object in a single statement, making the code more concise and readable.
WHEN NOT TO USE IT Do not use it if you need the return value from one of the intermediate methods. If a method in a chain returns a new or different object that you need for the next step, you must use standard dot notation. Cascade notation is strictly for performing multiple actions on the same initial object.
ONE CANONICAL EXAMPLE Configuring a Paint object in Flutter. Without cascades, you'd write: var paint = Paint(); paint.color = Colors.blue; paint.strokeWidth = 5.0;. With cascades, this becomes a single, fluent statement: var paint = Paint()..color = Colors.blue..strokeWidth = 5.0;. The expression evaluates to the configured Paint object, which is then assigned to the paint variable.
Read the original → dart.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.