The .. operator — Chaining Method Calls in Dart

Paul Edward Golez
2 min readApr 27, 2021

--

The cascade operator, .., is a convenient notation to invoke several instance methods from the same object within a single statement. With the right formatting, this make our code less verbose and easier to read.

It invokes the instance method then returns the instance

Using cascade notation over the usual dot operator(.) returns the instance itself instead of the actual return value of the (instance) method, allowing you to call another instance method within the same statement. As long as you use the .. , you can call other methods of that instance.

In the example above, the . operator, which happens to be a setter in this case, just returns the value it was set into. The .. operator performs the same method (assigning the customer value) but returns the instance which it was called on instead of the customer value.

It is a convenient alternative to a series of setters

With the cascade operator, it is possible to chain methods without modifying existing methods. In the example below, I can chain different methods without creating new ones (or overriding existing ones) specifically designed for chaining.

Don’t get me wrong. This is applicable to any instance method and not limited to setters!

Usage in Flutter

I first encountered this notation while watching Felix Angelov’s video on Cubits where he used the .. operator to override the current Snackbar with a new message.

Hiding and showing a snackbar with new content within the same statement

Just compare the difference between the cascading method implementation (above) with the original two-statement alternative (below).

An alternative implementation above using two statements

Isn’t this syntactic sugar sweet?

--

--

Paul Edward Golez

Software engineer from Cebu, Philippines. I write because I can.