The cascade notation (. .) in Dart allows us to make a sequence of operations on the same object (including function calls and field access). This notation helps keep Dart code compact and removes the need to create temporary variables to store data.
Let’s understand the cascade notation using the following code example.
import 'dart:convert';//An Example class with member attributes and methodsclass Example{var a;var b;void bSetter(b){this.b = b;}void printValues(){print(this.a);print(this.b);}}void main() {//Instantiating two Example objectsExample eg1 = new Example();Example eg2 = new Example();//Using the .. operator for operations on Example objectprint("Example 1 results:");eg1..a = 88..bSetter(53)..printValues();//The same operations as above but without the .. operatorprint("Example 2 results:");eg2.a = 88;eg2.bSetter(53);eg2.printValues();}
Let's go through the above code in detail.
Lines 5-6: The class named Example
has defined two variables a
and b
.
Lines 7-10: bSetter
is a method that takes a parameter b
and assigns it to the member variable b
of the class Example
.
Lines 11-14: printValues
prints the value of a
and b
.
Lines 19-20: Instantiating two example objects, such as eg1
and eg2
.
Lines 24-27: This part demonstrates the use of the cascade (..) operator in Dart. It allows us to perform multiple operations on the same object without repeating the object name.
Lines 31-33: This part demonstrates how the same operation can perform without cascade notation. This approach achieves the same result as the cascade notation by individually accessing the object's member variables and invoking methods using the dot notation. While the cascade notation allows multiple operations to be chained together more concisely.