我想在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);
无法引用级联源对象会阻止我在很多场合编写更短的代码。是否有更好的方法来进行方法级联?
答案 0 :(得分:2)
您无法按照自己的意愿使用this
。
您可以使用以下内容简化第二个代码段:
var button = getButton();
paragraph.append(button
..text = "Button A"
..onClick.listen((e) {
print (button.text + " has been has clicked");
}));