How do I reference "this" while method cascading in Dart?

138 Views Asked by At

I'd like to reference "this" (a method owner) while method cascading in Dart.

// NG code, but what I want.
paragraph.append( getButton()
    ..text = "Button A"
    ..onClick.listen((e) {
      print (this.text + " has been has clicked"); // <= Error. Fail to reference "button.text".
    }));

I know I can write a code like this by splitting it onto multiple lines.

// OK code, I think this is verbose.
var button;
button = getButton()
    ..text = "Button A"
    ..onClick.listen((e) {
      print (button.text + " has been clicked");
    }));
paragraph.append( button);

Being unable to reference a cascading source object is preventing me from writing shorter code on many occasions. Is there better way to do method cascading?

1

There are 1 best solutions below

1
Alexandre Ardhuin On BEST ANSWER

You can not use this as you would like.

You can simplify your second code snippet with :

var button = getButton();
paragraph.append(button
    ..text = "Button A"
    ..onClick.listen((e) {
      print (button.text + " has been has clicked");
    }));