
This short post walks you through a few examples of using the cascade notation (.., ? ) in Dart.
Table of Contents
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:Advertisements
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.
- 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
AdvertisementsThe 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
Weve 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 youd like to explore more new and interesting features in Dart and Flutter, take a look at the following posts:
- Dart: Convert Timestamp to DateTime and vice versa
- Dart & Flutter: Get the Index of a Specific Element in a List
- 2 ways to remove duplicate items from a list in Dart
- Dart regular expression to check peoples names
- Flutter: ListView Pagination (Load More) example
- Flutter & SQLite: CRUD Example
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.