Skip to content

unused_element_parameter should be issued when the only uses of a constructor parameter are inside the constructor itself. #62767

Description

@stereotype441

Consider the following code:

class _C {
  final int? _x;

  _C({int? x}) : _x = x;

  @override
  String toString() => '$_x';
}

void main() {
  print(_C());
}

This code doesn't produce the unused_element_parameter warning.

However, if the code is changed to use an initializing formal using the quick assist "Convert to an initializing formal parameter", then the resulting code looks like this:

class _C {
  final int? _x;

  _C({this._x});

  @override
  String toString() => '$_x';
}

void main() {
  print(_C());
}

...which does produce the unused_element_parameter warning.

Note: based on the warning code (unused_element_parameter), you might argue that technically, this is correct behavior, because in the first case, the value of the parameter is used, in the constructor initializer list. However:

  • The message text for the unused_element_parameter warning is "A value for the optional parameter 'x' isn't ever given.", which strongly suggests that the intention of this warning is to warn when the parameter is never used by the any caller of the constructor.
  • The behavior that is most useful to a user is to warn when the parameter is never used by the any caller of the constructor.

Note that the "Remove unused parameter" quick fix doesn't resolve the warning correctly. It produces:

class _C {
  final int? _x;

  _C();

  @override
  String toString() => '$_x';
}

void main() {
  print(_C());
}

...which has the static error final_not_initialized_constructor.

I believe the best way to solve this would be for both variants of the code to produce the warning.

Why this is important: with the feature "private named parameters" shipping soon, we would like to encourage users to upgrade their code to use that feature, by running dart fix --code=prefer_initializing_formals. It would be unfortunate if doing so led to new unused_element_parameter warnings that had to be fixed manually.

Metadata

Metadata

Assignees

Labels

P2A bug or feature request we're likely to work onarea-devexpFor issues related to the analysis server, IDE support, linter, `dart fix`, and diagnostic messages.devexp-warningIssues with the analyzer's Warning codesfeature-private-named-parameters

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions