Skip to content

add analyzer warning for unused variables in closures. #60952

Open
@TDuffinNTU

Description

@TDuffinNTU

Firstly, in other languages such as gdscript, if you don't use a variable provided by a parent class's function, you are recommended to preface it with an underscore. Similarly, in dart, if you don't use a variable provided in a closure signature, you can replace it with an underscore instead.

Provider<MyProvider> (
  create: (context) => MyProvider(), // Does not use context at all in this scope.
);

Is also find to be written as

Provider<MyProvider> (
  create: (_) => MyProvider(),
);

It would help enforce style guides if we could enforce this using a linter rule based on similar rules that check ahead for a token's use, and warning the developer if it isn't found later.


Conversely, you may run into an issue whereby you manually change these cases as above, but later you modify the contents of the closure to rely on a type that you've renamed, but is otherwise available outside of its scope:

Widget build(BuildContext context) {
  Provider<MyProvider> (
    create: (_) => MyProvider(someProp: context.read<SomeClass>()), // Now MyProvider needs context, but we're actually fetching it from outside its scope in the build method!
  );
}

While this is technically a second request, I think it would be pertinent to also add warnings for this case, too. Currently there is no warning or indication that you may be using variables out of scope which can risk some undefined behaviours (especially if relying on context for stateful objects!) that could be hard to diagnose at a glance.


I think these may be offered by some third party packages and/or services. While that might be a good interim solution, an official implementation (maybe of the latter at the very least) is something I would be keen to support. For packages, it can be hard to find one that has what you need (and not what you don't!) and for services there are some that are quite prohibitively expensive for their paid tiers.

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3A lower priority bug or feature requestarea-devexpFor issues related to the analysis server, IDE support, linter, `dart fix`, and diagnostic messages.devexp-linterIssues with the analyzer's support for the linter packagelinter-lint-proposaltype-enhancementA request for a change that isn't a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions