Skip to main content

Method Cascades in Dart

Posted by Gilad Bracha

(UPDATE: Method cascades are now implemented.)

The idea of a cascaded method invocation originates in Smalltalk, and has been proposed for Dart.  The motivation is to make it easier to write more fluent interfaces. 

Usually, fluent interfaces rely on method chaining. Say you want to add a large number of elements to a table:

// many lines elided here
// and here 
// and on and on

You might want to write this as

            // many lines elided here
            // and here 
            // and on and on

but this requires that add() return the receiver, myTokenTable, instead of the element you just added. The API designer has to plan for this, and it may conflict with other use cases. With cascades, no one needs to plan ahead or make this sort of tradeoff.  The add() method can do its usual thing and return its arguments. However, you can get a chaining effect using cascades:

// many lines elided here
// and here 
// and on and on

Here, ".." is the cascaded method invocation operation.  The ".." syntax invokes a method (or setter or getter) but discards the result, and returns the original receiver instead.

In brief, method cascades provide a syntactic sugar for situations where the receiver of a method invocation might otherwise have to be repeated. Instead of writing:

var address = getAddress();
address.setStreet(“Elm”, “13a”); = “Carthage”;
address.state = “Eurasia”, extended: 6666);

One may write

 ..setStreet(“Elm”, “13a”) = “Carthage”
 ..state = “Eurasia”, extended: 6666);

The sugar pays off the more complex the API, the longer the receiver of the cascaded method invocations, and the more methods are being directed toward that receiver. Cascades are expressions, so they also compose better than statements.  A cascade always evaluates to its initial receiver (the details are in the draft specification at the end of this document).

Below you'll find a number of examples, and a draft specification. As always, feedback is welcome. However, I'm about to go on vacation - so don't be offended if it takes a while before I respond to any of your comments.


The examples below show the use of the construct using a couple of indentation styles. All styles place cascaded access on a separate line, which improves readability.

Example 1

Consider using a (modified) String API:

String s = (new StringBuffer()
..add('Jenny ')
..add('I ')
..add('got ')
..add('your ')

Example 2

Another common example would be using a builder API

final addressBook = (new AddressBookBuilder() = 'jenny' = '' = (new PhoneNumberBuilder()
  ..number = '867-5309'
  ..label = 'home'

Example 3

class Point {
num x;
num y;

Point() {
  x = 0;
  y = 0;
void scale(num factor) {
 x *= factor;
 y *= factor;

// Hack to display debugging output while within a cascade. Naturally you can't use
// the regular print statement.
void log(String msg) {
 print ('logged ($x, $y): $msg');


void main(){

num x = 10;
num y = 42; // not used
var p = new Point();
 ..x = x
 ..y = x + p.x + p.y;
print('p.x = ${p.x}, p.y = ${p.y}. x = $x');


logged (0, 0): start
logged (100, 0): scaled
p.x = 101, p.y = 111, x = 10

Example 4

class Node {
String key;
Node left;
Node right;

void main() {
Node right = new Node('e');
Node root = new Node('root')
 ..left = (new Node('a')
   ..left = (new Node('b')
     ..left = new Node('c')
     ..right = Node('d')
 ..right = right;

Example 5

The following example is perhaps more typical of what you might do in a web application.

var dq = document.query('#mypanel').queryAll('TABLE .firstCol');
  ..background = 'red'
  ..border = '2px solid black'
dq.nodes.add(new Element.html('<span>This cell is now red</span>')) // ?

It might be even nicer if cascades nested, but the nesting makes things hard to read. 

document.query('#mypanel').queryAll('TABLE .firstCol')
   ..background = 'red'
   ..border = '2px solid black'
) ..nodes.add(new Element.html('<span>This cell is now red</span>')) // Not legal, just an idea for nesting

Maybe in the future we'll find a way to support such nesting in a truly readable way. For now we defer the issue and stick with one level of cascading.

Example 6

var dq = document.query('#myTable');
var qfc = dq.queryAll('.firstColumn');
   ..background = 'red'
   ..border = '2px solid black'
qfc.text = 'first column';

dq.queryAll('.lastColumn') = 'blue'
  ..text = 'last column';

Example 7
..position = 'absolute'
..left = '${_measuredLeft}px' = '${_measuredTop}px'
..width = '${_measuredWidth}px'
..height = '${_measuredHeight}px'
..zIndex = '${layoutParams.layer}'

Example 8

..fillStyle = penColor
..arc(tx, ty, penWidth/2+2, 0, PI2, true)
..moveTo(wx, wy)
..strokeStyle = "black"
..lineTo(tx, ty)

Example 9

        ..classes.remove('off') // ?
        ..classes.add('on') // ?

Example 10

Array access works as well

      ..['foo'] = bar
      ..['baz'] = bla


Here is an initial take on the specification for this proposal. Places where the current spec changes are highlighted in yellow.

A cascaded method invocation has the form e..suffix

where suffix is a sequence of operator, method, getter or setter invocations.

A cascaded method invocation expression of the form e..suffix is equivalent to the expression (t){t.suffix; return t;}(e).

Grammar Changes

topLevelExpression:      assignableExpression assignmentOperator cascade
   | conditionalExpression ('..' cascadeSection)*

primary:      thisExpression    | super assignableSelector
   | functionExpression
   | literal
   | identifier
   | newExpression
   | constantObjectExpression
'(' topLevelExpression ')'    ;

cascadeSection:     (assignableSelector arguments*)+ (assignmentOperator expression)?

Popular posts from this blog

A stronger Dart for everyone

We are constantly asking ourselves:
How do we make developers even more productive when writing Dart apps? We believe that a critical part of the answer to this question is to make strongmode – a sound static type system for Dart – the standard for all Dart developers.

Teams that use Dart to build apps like Soundtrap, AdWords, AdSense, and Greentea say they really enjoy using strong mode features, such as early error detection. In fact, teams that have switched completely to strong mode cite not only early error detection but also better code readability and maintainability as major benefits. We hear this both from small teams and Рeven more so Рfrom large teams with hundreds of developers writing and maintaining millions of lines of Dart code. As Björn Sperber from Soundtrap says,
Strong mode and the smooth integration with IntelliJ is a joy to use and a huge improvement. If you’ve tried out Flutter, you’ve already used strong mode checks from the Dart analyzer.

Given the benefits …

AngularDart 3.0: Easy upgrade, better performance

AngularDart 3.0 is now available. It brings better performance and smaller generated code, while also making you more productive.

Version 3.0 is an evolution: although it has some breaking changes (detailed below), it is a smooth upgrade due to minimal public API adjustments. Most of the progress is under the hood—in code quality, stability, generated code size, performance, and developer experience.

Code quality:
2731 instances of making the framework code more type safe (using sound Dart).The AngularDart framework code size is down by 12%.Many additional style updates to the codebase:Changed to use idiomatic <T> for generic methods.Removed NgZoneImpl, all the code exists in NgZone now.Stability:
Many CSS encapsulation fixes due to update with csslib package.Fixed bugs with IE11.

For the Mail sample app, we see 30% faster time-to-interactive (currently 3812 ms on a simulated 3G connection, measured via Lighthouse).Our large app benchmark shows 2x faster render times of…

Dart 1.24: Faster edit-refresh cycle on the web & new function type syntax

Dart 1.24 is now available. It includes the Dart Development Compiler and supports a new generic function type syntax. Get it now!

Figure 1: DDC debugging in Chrome.

Some notable changes in this release:
pub serve now has support for the Dart Development Compiler. Unlike dart2js, this new compiler is modular, which allows pub to do incremental re-builds for pub serve.In practice what that means is you can edit your Dart files, refresh in Chrome (or other supported browsers), and see your edits almost immediately. This is because pub is only recompiling your package, not all packages that you depend on.There is one caveat with the new compiler, which is that your package and your dependencies must all be strong mode clean.You can also use the new compiler to run your tests in Chrome much more quickly than you can with dart2js.Read more in the changelog.You can now publish packages that depend on the Flutter SDK to pub. Moreover, has started tagging Flutter plugins with …