Cascade notation in Dart Programming


Cascade notation is used when we want to operate a sequence of operations on the same object. The cascade notation is denoted by the (..) symbol.

It is similar to method chaining that we have in other programming languages and it does save us plenty of steps and need of temporary variable.

Example

Consider the following example for a representation of how the cascade notation works in Dart.

 Live Demo

class Sample{
   var a;
   var b;
   void showA(x){
      this.a = x;
   }
   void showB(y){
      this.b = y;
   }
   void printValues(){
      print(this.a);
      print(this.b);
   }
}
void main(){
   Sample sampleOne = new Sample();
   sampleOne.showA(2);
   sampleOne.showB(3);
   sampleOne.printValues();

   Sample sampleTwo = new Sample();
   sampleTwo..showA(2)
   ..showB(3)
   ..printValues();
}

In the above example, we have two objects created of a single class and we are calling three methods that are present in the above class. When we call the three methods on the object instance sampleOne, we are explicitly typing the name of the object three times followed by the dot notation and the call to methods.

In the second case, the sampleTwo is written only once and we made use of the cascade operator to call the methods we want.

It should be noted that we can't have semicolons(;) between the consecutive method calls as it will confuse the compiler and we will get an error.

Output

2
3
2
3

Updated on: 21-May-2021

934 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements