As stated in the dart article:
The ".." syntax invokes a method (or setter or getter) but discards the result, and returns the original receiver instead.
So I assumed that this would work:
myList..clear().addAll(otherList);
which gave me the error that I can't call .addAll
on null
.
So apparently .
precedes ..
so that .addAll
has been invoked on the result of .clear()
.
I figure now that I have two possibilities to write this:
myList..clear()..addAll(otherList);
(myList..clear()).addAll(otherList);
(If I wanted to get the result of.addAll()
.
Is this correct? If yes, why the decision to give .
precedence? It seems very counterintuitive. Is it to avoid syntax like this: myList(..clear().useResultOfClear()).addAll(otherList);
?
As pointed in the official Dart language article Method Cascades in Dart:
Below are example based/copied from the previously cited article. For further information, go read it.
add()
exampleIn the scenario where one want to add multiple elements to a list, the legacy-way is to do multiple assignements :
While you can't do something like
myList.add("item1").add("item1")….add("itemN");
as theadd()
does not method return themyList
object but avoid
, you can use the cascading operator instead as it discards the result, and returns the original receivermyList
:Another example
So Instead of writing:
One may write
Further reading
If you want to know more about cascading method, I wrote an article by adding information that goes behind the scope of this question.
You can read the article from Gilad Bracha : Method Cascades in Dart. At its ends, you will see many examples.
See also this answer of Lasse Nielsen about operator precedence :
Basically,
a..b().c()
is the same as(t){t.b().c(); return t;}(a)