Skip to content

Reduce usage of context getters and globals in the flutter tool #47161

@jonahwilliams

Description

@jonahwilliams

Internal: b/139713315

The flutter_tool currently makes heavy usage of context getter globals to inject objects throughout the tool for both configuration and testability issues. For example:

Foo get foo => context.get<Foo>();

class Bar {

  void doThing() {
    foo.fizz(); // context global
  }
}

This is making it more difficult than necessary to unit test tooling code. Besides mocking foo, we must also ensure the context injection is correct which leads to a significant amount of boilerplate configuration for each test case. Mistakes in this boilerplate can lead to tests silently doing the wrong thing.

Previously I attempted to clean this up with the Testbed class, but this hasn't succeeded it simplifying the test cases.

Instead, we should gradually reduce our usage of these context getters which removes the need for the test configuration and makes it more explicit which instances are being used for tests. For example, rewriting the snippet above becomes:

class Bar {
  Bar({Foo foo}) : _foo = foo;

  final Foo _foo;

  void doThing() {
    _foo.fizz();
  }
}

To ensure we don't regress in usage of context getters, we can use the forthcoming testWithoutContext test method that throws if context.get is invoked. See also #45739

cc @zanderso

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3Issues that are less important to the Flutter projectc: contributor-productivityTeam-specific productivity, code health, technical debt.team-toolOwned by Flutter Tool teamtoolAffects the "flutter" command-line tool. See also t: labels.tool-still-validIssues that have been deemed still valid as part of the Flutter Tools issue cleanup initiative.triaged-toolTriaged by Flutter Tool teamwould require significant investmentA PR would not be accepted without a plan for ongoing support

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions