Using Cascade Notation in Dart and Flutter

Last updated on August 12, 2021 Guest Contributor Loading... Post a comment

This short post walks you through a few examples of using the cascade notation (.., ?…) in Dart.

What Is The Point?

In Dart, cascades let you execute a sequence of operations on the same object. In other words, cascades allow you to perform a chain of methods without the need for temporary variables. In general, they will look like this:

myObject..method1()..method2()..method3();
myList?..method1()..method2()..method3()..method4();

For more clarity, see the examples below.

Example 1: Cascades and a List

The two code snippets below do the same thing.

  1. Using cascades:
void main() {
  List myList = [1, 2, 3];
  myList
    ..clear()
    ..add(4)
    ..add(5)
    ..add(6);

  print(myList);
}

// Output: [4, 5, 6]

2. Not using cascades:

void main() {
  List myList = [1, 2, 3];
  myList.clear();
  myList.add(4);
  myList.add(5);
  myList.add(6);
  print(myList);
}

// Output: [4, 5, 6]

Example 2: Cascades and a Class

The code:

class Person {
  String? name;
  int? age;

  void setName(String name) {
    this.name = name;
  }

  void setAge(int age) {
    this.age = age;
  }

  void printInfo() {
    print("User name: ${this.name ?? 'Unknown'}");
    print("User age: ${this.age ?? 'Not provided'}");
  }
}

void main() {
  new Person()
    ..setName('Kindacode.com')
    ..setAge(4)
    ..printInfo();

  final instance = new Person();
  instance
    ..setName('John Doe')
    ..setAge(99)
    ..printInfo();
}

Output:

// Person 1
User name: Kindacode.com
User age: 4

// Person 2
User name: John Doe
User age: 99

Conclusion

We’ve gone through a couple of examples of using cascades in Dart. At this point, you should have a better understanding and get a comfortable sense of reading and writing concise and compact code with this syntax. If you’d like to explore more new and interesting features in Dart and Flutter, take a look at the following posts:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like