-
Notifications
You must be signed in to change notification settings - Fork 29k
Description
Apps regularly want to respond to a stream of events that might be coming from non-UI related sources (such as network or platform channels). Common responses to such events might include:
- Navigating to a new page.
- Showing a dialog.
- Showing a snackbar.
Such events are typically not tied to the lifecycle of the "current page". The BuildContext
of the code that invokes the action could be long gone when the action finally resolves.
A few examples:
final value = await permissionPluginCall();
Navigator.of(context).pushNamed(‘xxx’);
try {
final value = await someRpcCall();
} catch (e, st) {
Scaffold.of(context).showSnackBar(...)
}
try {
await someCode();
} catch (e, st) {
ErrorDisplayWidget.of(context).handleException(...)
}
There are solutions around some of these problems such as using NavigatorKey however, I have not seen a canonical way to grab a valid (aka current) context from anywhere in the app.
The ideal outcome of this issue would be to have a pattern similar to InheritedWidget.of(context)
which locates the current context for you. Something like InheritedWidget.current
.
Workarounds I have seen are pretty terrible:
- Passing
BuildContext
around. - Passing
State
around. - Using APIs such as
context.findRenderObject().attached
to determine whether context is still valid.