Featured
- Get link
- X
- Other Apps
Dart`s Cascade Notation (.., ?..)
In Dart programming language, cascades (.., ?..) allow you to make a sequence of operations on the same object. In addition to accessing instance members, you can also call instance methods on that same object. This often saves you the step of creating a temporary variable and allows you to write more fluid code.
Consider the following code:
var paint = Paint()
..color = Colors.black
..strokeCap = StrokeCap.round
..strokeWidth = 5.0;
The constructor, Paint(), returns a Paint object. The code that follows the cascade notation operates on this object, ignoring any values that might be returned.
The previous example is equivalent to this code:
var paint = Paint();
paint.color = Colors.black;
paint.strokeCap = StrokeCap.round;
paint.strokeWidth = 5.0;
If the object that the cascade operates on can be null, then use a null-shorting cascade (?..) for the first operation. Starting with ?.. guarantees that none of the cascade operations are attempted on that null object.
querySelector('#confirm') // Get an object.
?..text = 'Confirm' // Use its members.
..classes.add('important')
..onClick.listen((e) => window.alert('Confirmed!'))
..scrollIntoView();
Version note: The ?.. syntax requires a language version of at least 2.12.
The previous code is equivalent to the following:
var button = querySelector('#confirm');
button?.text = 'Confirm';
button?.classes.add('important');
button?.onClick.listen((e) => window.alert('Confirmed!'));
button?.scrollIntoView();
You can also nest cascades. For example:
final addressBook = (AddressBookBuilder()
..name = 'jenny'
..email = 'jenny@example.com'
..phone = (PhoneNumberBuilder()
..number = '415-555-0100'
..label = 'home')
.build())
.build();
Be careful to construct your cascade on a function that returns an actual object. For example, the following code fails:
var sb = StringBuffer();
sb.write('foo')
..write('bar'); // Error: method 'write' isn't defined for 'void'.
The sb.write() call returns void, and you can’t construct a cascade on void.
Note: Strictly speaking, the “double dot” notation for cascades isn’t an operator. It’s just part of the Dart syntax.
- Get link
- X
- Other Apps
Popular Posts
Building a gRPC Service with Nested Messages, Repeated Fields, and Oneof in Python
- Get link
- X
- Other Apps
How the Diffie-Hellman Exchange Works: An Example in Python
- Get link
- X
- Other Apps
Comments
Post a Comment