-
Notifications
You must be signed in to change notification settings - Fork 29.8k
Description
Use case
Related to:
- [Discussion] Scope spanning multiple screens #30062 (a use-case for such a feature)
- Expose InheritedWidget subscription cancelation #33213 (previous attempt at implementing this)
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.