Reputation: 7050
According to official Dart documentation, it is mentioned that:
Chaining method calls
a..b = true..c = 5;
Cascade used for chaining access to methods and other members. Equivalent:
a.b = true; a.c = 5;
Can someone explain the meaning of the above lines?
Upvotes: 2
Views: 819
Reputation: 7050
Cascades
To perform a sequence of operations on the same object, use cascades (..). We’ve all seen an expression like this:
myObject.someMethod()
It invokes someMethod()
on myObject
, and the result of the expression is the return value of someMethod()
.
Here’s the same expression with a cascade:
myObject..someMethod()
Although it still invokes someMethod()
on myObject
, the result of the expression isn’t the return value — it’s a reference to myObject
! Using cascades, you can chain together operations that would otherwise require separate statements. For example, consider this code:
var button = querySelector('#confirm');
button.text = 'Confirm';
button.classes.add('important');
button.onClick.listen((e) => window.alert('Confirmed!'));
With cascades, the code becomes much shorter, and you don’t need the button variable:
querySelector('#confirm')
..text = 'Confirm'
..classes.add('important')
..onClick.listen((e) => window.alert('Confirmed!'));
Upvotes: 1
Reputation: 3193
Consider user
as an instace of following class:
class User {
int age;
String firstName;
String lastName;
}
Now you can update data in user
as following:
user.age = 5;
user.firstName = 'John';
user.lastName = 'Doe';
but if you use chaining access as described in the documentation. Then it will look something like this:
user..age = 5
..firstName = 'John'
..lastName = 'Doe';
Note: sequence of assignment of the properties does not matter, but it might be of importance while calling functions or methods like this.
Just a simple & random example:
painter..computeLayout()
..initializePaint()
..render();
above is same as:
painter.computeLayout();
painter.initializePaint();
painter.render();
in the above example all of the methods were called on painter
object/instance but the sequence here must be followed as without paint or layout the render will not work.
Upvotes: 3