Dart makes working with objects simple, often letting you avoid extra code commonly used in other languages.
The "Useless" Approach
Sometimes, developers create extra classes or methods just to set properties on an object in a chained way. The image shows an example of a MyModelBuilder
class with methods like setName
, setTitle
, and setCount
that all return the builder itself, ending with a build
method.
Why It's Useless in Dart
Dart has built-in features that make this kind of builder pattern unnecessary for simple object creation and configuration.
The Dart Way: Cascade Notation
What is Cascade Notation?
Dart introduces a special syntax called "cascade notation", represented by ..
. This notation is incredibly useful.
How to Use It
You can directly use the cascade notation to make a sequence of operations on the same object. Look at the example main
function in the image. Instead of creating a MyModelBuilder
, you can create the MyModel
directly and then use ..name
, ..title
, and ..count
to set its properties.
Cleaner Code
This approach is much cleaner because you don't need to write separate methods (like setName
, setTitle
, etc.) that just return this
. You simply chain the operations using ..
.
Benefit
Dart's cascade notation lets you achieve the same goal as a traditional builder (configuring an object step-by-step) with less code and better readability for simple cases.