I want to show an overlay on the whole app so I tried to insert an overlay entry on the context of MaterialApp (root widget) but the problem is I’m getting the null value on invoking the following method :
Overlay.of(context);
GetMaterialApp.router(
debugShowCheckedModeBanner: false,
theme: AppTheme.lightTheme,
scaffoldMessengerKey: Keys.scaffold,
scrollBehavior: MyCustomScrollBehavior(),
routeInformationParser: WebRoutes.goRouter.routeInformationParser,
routerDelegate: WebRoutes.goRouter.routerDelegate,
routeInformationProvider: WebRoutes.goRouter.routeInformationProvider,
builder: (context, child) {
WidgetsBinding.instance.addPostFrameCallback((_){
addOverlay(context);
});
return child;
}
void addOverlay(BuildContext context) {
print(Overlay.of(context));
return Overlay.of(context)?.insert(OverlayEntry(
builder: (context) {
return SomeWidget();
},
));
}
Is there any way to get the state of overlay using the context of this root widget as I want to show the overlay globally.
Thanks alot, I really appreciate that If someone helps me.
3
Answers
You can achieve that by create a class responsible to display/remove the overlay, this class need receive a
BuildContext
when creating to be able to create an instance ofOverlay
.Basically what you need to do are:
Create a class
OverlayScreen
that build theOverlayState
&&OverlayEntry
(in this case theOverylayEntry
will be a list of OverlayEntry since we might have more than one Overlay on the screen so we can remove all of them at once).Create an instance of this class earlier in your app (e.g MyApp). In your case you’ll need to call this inside Material.router…builder param.
Access this
overlayScreen
in your HomePage to display|removeAll overlaysLets create our OverlayScreen
Now lets create an instance on
MyApp
To finalise lets create our
HomePage
and access ouroverlayScreen
there thereThat’s it. You can use this class OverlayScreen to show/removeAll wherever you want.
I created a PR with sample code, check it out https://github.com/antonio-nicolau/flutter-working-with-overlay