Cascade Operator in Dart

Sohel Akhtar
1 min readJul 7, 2022

Cascades (.., ?..) allow you to make a sequence of operations on the same object. In addition to accessing instance members, you can also call instance methods on that same object. This often saves you the step of creating a temporary variable and allows you to write more fluid code.

The Cascades notation(..) is similar to method chaining that saves you a number of steps and the need for a temporary variable.

Consider the following code:

var paint = Paint()
..color = Colors.black
..strokeCap = StrokeCap.round
..strokeWidth = 5.0;

The constructor, Paint(), returns a Paint object. The code that follows the cascade notation operates on this object, ignoring any values that might be returned.

The previous example is equivalent to this code:

var paint = Paint();
paint.color = Colors.black;
paint.strokeCap = StrokeCap.round;
paint.strokeWidth = 5.0;

Another Example

In the example below, we have created an Example class with two methods (bSetter & printValues).

In line 24-27, we are using dart cascade notation for operations on Example class object eg1.

I hope you now have the concept of using the cascade operator(..)

Thanks for reading along. Leave some claps!!!

--

--