Sometimes I see this
List list = [];
Then list..add(color)
Whats the difference in using 1 dot(.
) and 2 dot(..
)?
Sometimes I see this
List list = [];
Then list..add(color)
Whats the difference in using 1 dot(.
) and 2 dot(..
)?
..
is known as cascade notation. It allows you to not repeat the same target if you want to call several methods on the same object.
List list = [];
list.add(color1);
list.add(color2);
list.add(color3);
list.add(color4);
// with cascade
List list = [];
list
..add(color1)
..add(color2)
..add(color3)
..add(color4);
It's the cascade operator of Dart
var l1 = new List<int>()..add(0)..addAll([1, 2, 3]);
results in l1
being a list [0, 1, 2, 3]
var l1 = new List<int>().add(0).addAll([1, 2, 3]);
results in an error, because .add(0)
returns void
..
(in the former example) refers to new List()
,
while .
(in the later) refers to the return value of the previous part of the expression.
..
was introduced to avoid the need to return this
in all kinds of methods like add()
to be able to use an API in a fluent way.
..
provides this out of the box for all classes.
Cascades (..) allow you to make a sequence of operations on the same object. read doc for details
querySelector('#confirm') // Get an object.
..text = 'Confirm' // Use its members.
..classes.add('important')
..onClick.listen((e) => window.alert('Confirmed!'));
The previous example is equivalent to:
var button = querySelector('#confirm');
button.text = 'Confirm';
button.classes.add('important');
button.onClick.listen((e) => window.alert('Confirmed!'));