Skip to content

Add a way to react to when a widget stops listening to an InheritedWidget #106546

@rrousselGit

Description

@rrousselGit

Use case

Related to:

Currently, while it is possible to lazily initialize an InheritedWidget, there is no way for InheritedWidgets to perform an action when they stop being listened.

This limitation prevents package:riverpod from using the context API to implement the package, as it needs such an API for a core:

  • autoDispose, which is used to free the resources linked to an InheritedWidget when that InheritedWidget stops being used.

This leads to an ugly workaround, which is subclassing StatelessWidget/StatefulWidget to override Element.build (cf ConsumerWidget, a custom StatelessWidget-like)

While this workaround works, it has an important downside:
This leads to package:riverpod being used differently from what Flutter typically does.
Instead of a:

class Example extends StatelessWidget {
  Widget build(BuildContext context) {
    MyInheritedWidget.of(context);
  }
}

Riverpod users have to do:

class Example extends ConsumerWidget {
  Widget build(BuildContext context, WidgetRef ref) {
    MyInheritedWidget.of(ref);
  }
}

This difference is the reason why I had to basically stop developing package:provider and instead start working on package:riverpod, as package:provider couldn't keep using the context syntax while supporting autoDispose which is a core feature for numerous commonly requested enhancements.

Adding a way for InheritedWidgets/InheritedElements to perform actions when a dependent is removed (along with changing the behavior described here #12992 (comment) ) would allow package:riverpod to use the context API instead of having to implement a custom StatelessWidget/ConsumerWidget

Proposal

A pull request was previously made for this feature but was closed: #33213
This issue would involve re-opening that closed PR and merging it instead.

But I am open to finding a different way of implementing this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3Issues that are less important to the Flutter projectc: new featureNothing broken; request for a new capabilityc: proposalA detailed proposal for a change to Flutterframeworkflutter/packages/flutter repository. See also f: labels.team-frameworkOwned by Framework teamtriaged-frameworkTriaged by Framework team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions