-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Description
If you want to initialize a private instance field from a named parameter, you currently have to write an explicit initializer like:
class House {
int? _bedrooms;
House({int? bedrooms}) : _bedrooms = bedrooms;
}
main() {
House(bedrooms: 3);
}With the upcoming "Private Named Parameters" feature, you can instead write:
class House {
int? _bedrooms;
House({this._bedrooms});
}
main() {
House(bedrooms: 3); // Still uses public name.
}Likewise with primary constructors:
class House({final int? _bedrooms});
main() {
House(bedrooms: 3); // Still uses public name.
}I believe we should have a lint encouraging users to use a private named parameter instead of the current manual pattern (#62239). To go with that, we should have a quick fix that addresses the lint (this issue). The change the quick fix should apply is:
-
If the constructor is a primary constructor the named parameter and the corresponding instance field have the same type:
- Prepend
_to the named parameter's name. - Prepend the parameter with
finalif the field is final orvarif not to make the parameter declaring. - If there are any metadata annotations on the instance variable declaration, move them to the parameter.
- Likewise move any doc comment on the instance variable to the parameter.
- Prepend
-
Else (normal generative constructor, or primary constructor whose parameter has a different type):
- Prepend
_to the named parameter's name. - Prepend
this.to make it an initializing formal. - If the parameter's type is the same as the corresponding field's, then remove the type annotation from the parameter.
- Remove the
_foo = foofrom the initializer list. If there are no other initializers, remove the:too.
- Prepend
-
If any doc comments reference the named parameter, update them to use the private name.