Dart 如何匹配类的构造函数中的命名参数?
示例(有效):
Class MyWidget {
final String a;
final String b;
MyWidget (
@required this.a,
@required this.b
)
@override // Yes, it's Flutter
Widget build(BuildContext context) {
return ....
}
}
/// Calling MyWidget
return MyWidget(
a: x,
b: y
)
Run Code Online (Sandbox Code Playgroud)
This works as expected. But in this setup I am forced to name the variable in MyWidget the same as the Named Parameter because the 'a' in the call is the same as the 'this.a' in the MyWidget.
What I would like is something like this:
Class MyWidget {
final String aaa;
final String bbb;
MyWidget (
@required a // And assign that value to this.aaa,
@required b // And assign that value to this.bbb
)
}
Run Code Online (Sandbox Code Playgroud)
How do I assign the value of passed Named Parameter 'a' to local variable 'aaa'?
您必须this.xxx像这样权衡语法的简单性:
class MyWidget {
final String aaa;
final String bbb;
MyWidget({a, b})
: aaa = a,
bbb = b;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
965 次 |
| 最近记录: |