Reputation: 2676
How does Dart match the named parameters in a Constructor of a Class?
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.
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'?
Upvotes: 2
Views: 1775
Reputation: 51768
You have to trade off the simplicity of the this.xxx
syntax like this:
class MyWidget {
final String aaa;
final String bbb;
MyWidget({a, b})
: aaa = a,
bbb = b;
}
Upvotes: 8