What is cascade notation or method chaining in Dart

Use of cascade notation in dart :

Cascade notation or (..) is used for method chaining in dart. With method chaining, you can create one single object with a sequence of methods. It is like a different concise way to create one object.

In this post, I will show you how to use cascade notation or method chaining in dart with examples.

Cascade notation example :

Suppose, you want to create one button object with button text and one onClick listener. This is what we do normally :

var clickButton = querySelector('#submit');
clickButton.text = 'Submit';
clickButton.onClick.listen((e) => {
    // your code for onClick
})

And using cascade notation, you can do the same steps as below :

var clickButton = querySelector('#submit')
                ..text = 'Submit'
                ..onClick.listen((e) => {
                    // code for onClick
                })

Example program :

Let me show you a simple example :

class NumberBuilder{
  int num;

  NumberBuilder(int n){
    num = n;
  }

  multiply(int n){
    num *= n;
  }

  add(int n){
    num += n;
  }

  subtract(int n){
    num -= n;
  }
}

main() {
  var i = new NumberBuilder(4)
          ..add(5)
          ..multiply(3)
          ..subtract(7);
  print(i.num);
}

In this example, NumberBuilder class has one integer variable num defined in it. Using the add, multiply and subtract, we can change it. We are creating one NumberBuilder variable in the main method. It will print 20 as the output.

Dart cascade notation

Cascade is useful for building a complex object in a better way, with less code. Cascade or method chaining is available in many object-oriented programming languages. This is also a good dart coding practice.