Skip to content

Quick fix to convert code to use private named parameter #62240

@munificent

Description

@munificent

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 final if the field is final or var if 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.
  • 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 = foo from the initializer list. If there are no other initializers, remove the : too.
  • If any doc comments reference the named parameter, update them to use the private name.

cc @bwilkerson @scheglov

Metadata

Metadata

Assignees

Labels

area-devexpFor issues related to the analysis server, IDE support, linter, `dart fix`, and diagnostic messages.devexp-quick-fixIssues with analysis server (quick) fixesfeature-private-named-parameters

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions