thumbnail

Cascade Operator In Dart

Published on 29 March 2020
Last Updated on 29 March 2020

Use of Cascades (..) Operator In Dart

Cascades operator in Dart can be used for performing a sequence of operations on same objects, in addition to that, you can also perform function calls.

Using cascade operator, you can eliminate a lot redundancies.

Sample code that makes use of Cascade Operator

// sample code that does not make use of cascade operator
void noCascade() {
  var sb = StringBuffer();
  sb.write('hello\n');
  sb.write('world!\n');
  sb.write('a\n');
  sb.write('b\n');
  sb.write('c\n');
  sb.write('d\n');
  sb.write('e\n');
  print(sb.toString());
}

// sample code that makes use of cascade operator
void cascade() {
  print((StringBuffer()
        ..write('hello\n')
        ..write('world!\n')
        ..write('a\n')
        ..write('b\n')
        ..write('c\n')
        ..write('d\n')
        ..write('e\n'))
      .toString());
}

main(List<String> args) {
  noCascade();
  cascade();
}

Above program produces following output:

hello
world!
a
b
c
d
e

hello
world!
a
b
c
d
e

As you can see, both functions produce same output however, second function looks more fluid as compared to first function. Also second function is more compact than first function and does not include any redundancies.

Example 2 using Cascade Operator

Example given below demonstrates how cascade operator can be used on custom data types.

class Person {
  String firstName;
  String lastName;
  void sayHello() {
    print('Hello ${firstName} ${lastName}!');
  }
}

main(List<String> args) {
  Person()
    ..firstName = 'john'
    ..lastName = 'doe'
    ..sayHello();
}

Above program produces following output:

Hello john doe!

We hope that you have found this guide for learning how to use Cascade Operator in Dart.