1

我想在 Dart 中级联方法时引用“this”(方法所有者)。

// 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".
    }));

我知道我可以通过将其拆分为多行来编写这样的代码。

// 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);

无法引用级联源对象使我无法在很多情况下编写更短的代码。有没有更好的方法进行方法级联?

4

1 回答 1

2

您不能随意使用this

您可以使用以下方法简化第二个代码段:

var button = getButton();
paragraph.append(button
    ..text = "Button A"
    ..onClick.listen((e) {
      print (button.text + " has been has clicked");
    }));
于 2014-03-06T16:48:06.920 回答