Let's continue with the aforementioned, less than optimal code and reimplement it with cascades:
- Recreate the UrlBuilder class, but without any of the extra methods that are usually required to implement this pattern. This new class will not look that different from a mutable Dart object:
class UrlBuilder {
String scheme;
String host;
List<String> routes;
@override
String toString() {
assert(scheme != null);
assert(host != null);
final paths = [host, if (routes != null) ...routes];
final path = paths.join('/');
return '$scheme://$path';
}
}
- Next, you are going to use the cascade operator to get the builder pattern for free. Write this function just after the declaration of the UrlBuilder class:
void cascadePlayground() {
final url = UrlBuilder()
..scheme = 'https'
..host = 'dart.dev'
..routes = [
'guides',
'language',
'language-tour#cascade-notation-',
];
print(url);
}
- The cascade operator is not exclusively used for the builder pattern. It can also be used to, well, cascade similar operations on the same object. Add the following code inside the cascadePlayground function:
final numbers = [342, 23423, 53, 232, 534]
..insert(0, 10)
..sort((a, b) => a.compareTo(b));
print('The largest number in the list is ${numbers.last}');