What is Dart cascade notation?
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.
Code
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();}
Code example
Let's go through the above code in detail.
Lines 5-6: The class named
Examplehas defined two variablesaandb.Lines 7-10:
bSetteris a method that takes a parameterband assigns it to the member variablebof the classExample.Lines 11-14:
printValuesprints the value ofaandb.Lines 19-20: Instantiating two example objects, such as
eg1andeg2.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.
Free Resources