Dart Cascade Notation
Dart Cascade Notation
An object is a value that has its own methods, like a string, a list or a StringBuffer.
Often you want to call many methods on the same object.
Without cascades, you must write the variable name again on every line:
Example
void main() {
var buffer = StringBuffer();
buffer.write('Hello');
buffer.write(', ');
buffer.write('World');
print(buffer);
}
Try it Yourself »
Result:
Hello, World
A StringBuffer is a built-in object that builds a string piece by piece.
The write() method adds text to the end of it.
The .. Operator
The cascade operator .. lets you do many operations on the same object, one after another.
You write the object one time, and start every operation with ..:
Example
void main() {
var buffer = StringBuffer()
..write('Hello')
..write(', ')
..write('World');
print(buffer);
}
Try it Yourself »
Result:
Hello, World
Only the last line ends with a semicolon, because the whole cascade is one statement.
Cascades with Lists
Cascades work with any object.
Here we use a list, a group of values in square brackets (you will learn more in the Lists chapter):
Example
void main() {
var fruits = ['Banana']
..add('Cherry')
..add('Apple')
..remove('Banana');
print(fruits);
}
Try it Yourself »
Result:
[Cherry, Apple]
A Cascade Returns the Object
A normal method call gives you the result of the method.
A cascade gives you the object itself, not the result of the method.
For example, sort() sorts a list but returns nothing, so this program does not run:
Result:
main.dart:3:9: Error: This expression has type 'void' and can't be used.
print(numbers);
^
With ..sort(), you get the sorted list back:
Result:
[1, 2, 3]
The ?.. Operator
If the object can be null, start the cascade with ?.. instead.
The whole cascade is skipped when the object is null:
Example
StringBuffer? log = StringBuffer();
StringBuffer? noLog;
void main() {
log
?..write('Started')
..write(' and finished');
print(log);
noLog
?..write('Started')
..write(' and finished');
print(noLog);
}
Try it Yourself »
Result:
Started and finished
null
Note: Only the first operation needs ?.., the rest of the cascade uses ...