Dart Cascade symbol — “..”

Cascading expressions (..) Allows you to use operators continuously on the same object.

In addition to method calls, you can also get member variables on the same object. This usually eliminates the need to create temporary variables, while allowing you to write smoother code.

Strictly speaking, the two points of a cascading expression (“.. The “) syntax doesn’t count as an operator, it’s just part of Dart’s syntax.

Here, ".." is the cascaded method invocation operation.  The ".." syntax invokes a method (or setter or getter) but discards the result, and returns the original receiver instead. 
Copy the code

“..” Is the cascading method call operator. ..” The syntax calls a method (getter or setter) and dismisses its return value, while returning the original recipient of the cascade operator.

In brief, method cascades provide a syntactic sugar for situations where the receiver of a method invocation might otherwise have to be repeated. 
Copy the code

In short, method cascade operators are syntactic sugar for situations where the receiver of a method call repeats.

Example 1

We define a Student object, then create a Student object, calling its methods and setter properties in turn through a cascading expression.

class Student {
  String string;

  void testMethod() {
    print("This is a test method");
  }

  void testMethod1() {
    print("This is a test method1");
  }

  String printString() {
    print("string: $string");
    returnstring; }}main() { Student() .. testMethod() .. testMethod1() .. string ="The cat mewed."
    ..printString();
}
Copy the code

The cascading expression calls above are equivalent to the calls below.

main() {
  var student = Student();
  student.testMethod();
  student.testMethod1();
  student.string = "The cat mewed.";
  student.printString();
}
Copy the code

By comparison, it is apparent that there is no temporary variable stud

Example 2

When you use cascading expressions on methods that return a specific value, note that cascading expressions cannot be used on void types.

var result = StringBuffer()
                 .write('foo')
                 ..write('bar');
Copy the code

// Error: method ‘write’ isn’t defined for ‘void’.

Because the StringBuffer#write method returns void, you cannot use cascading expressions on void types.

We can continue using the cascading expression with a few modifications, as follows:

main(){ var result = StringBuffer() .. write('foo')
                 ..write('bar');

  print('result:$result'); // result:foobar
}
Copy the code

Summary – Application scenario

In short, when we need to perform multiple operations on the same object, we can consider using cascading expressions to simplify our operations and make successive calls to the same object.

Reference:

cascade-notation

Method Cascades in Dart

dart-programming-cascade-operator