What is cascade notation in dart?

The cascade notation (. .) in Dart allows you 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.

In general, they will look like this:

myObject..method1()..method2()..method3(); 

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

Example 1: Cascades and a List

The two code snippets below do the same thing.

1. Using cascades:

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

  print(myList);
}

// Output: [4, 5, 6]

2. The code snippet below rewrites the preceding example but not using cascade:

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:

// Define a class called "Person" with "name" and "age" properties
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: ${name ?? 'Unknown'}");
    print("User age: ${age ?? 'Not provided'}");
  }
}

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

  final instance = Person();
  instance
    ..setName('Jon doe')
    ..setAge(99)
    ..printInfo();
}
//output

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

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

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.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More