[英]Dart: How does Dart match the named parameters in a Constructor of a Class?
How does Dart match the named parameters in a Constructor of a Class? Dart如何在类的构造函数中匹配命名的参数?
Example (which works) : 示例(有效):
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
)
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.
但是在此设置中,由于调用中的“ a”与MyWidget中的“ this.a”相同,因此我不得不在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
)
}
How do I assign the value of passed Named Parameter 'a' to local variable 'aaa'? 如何将传递的命名参数“ a”的值分配给局部变量“ aaa”?
You have to trade off the simplicity of the this.xxx
syntax like this: 您必须权衡
this.xxx
语法的简单性,如下所示:
class MyWidget {
final String aaa;
final String bbb;
MyWidget({a, b})
: aaa = a,
bbb = b;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.