How to use double dot operator- Cascade operator in Dart| Flutter

cascade operator is used to call a sequence of methods on the objects using .. double dot operator.

For example, you have a list object and want to call the same add method for multiple values.

You will call as below

List list = [];

The object name list is repeatedly called to do the same operation. You can also do multiple operations on the same object. Cascade operator (..) is introduced to avoid the repeated current object instance name.

Dart Cascade operator

The Cascade operator is also called the double dot operator.

It is used to chain operations piped using a double dot by ignoring return values.



instance..method1 returns this object.

The same can be rewritten using

main() {
  List list = [];

It is helpful for developers to build objects faster with few lines of code.

Null Shorting Cascade notation for null safety in dart

Sometimes, the Object that you call the double dot operator might be null, In that case, a null shorting cascade(? ..) is being used.

var employee = Employee(); = 1; ="John";
employee.salary = 5000;

The above code was replaced with a cascade operation

var employee = Employee() = 1; ="John";
..salary = 5000;

Next, add the null shorting operator(?) for the first cascade operation for null safety

var employee = Employee()
? = 1; ="John";
..salary = 5000;

which is equal to

var employee = Employee();
employee?.id = 1;
employee?.name ="John";
employee?.salary = 5000;