Reputation: 37
Please help!
I have initiated the overlay from a separate class, (calling the showOverlay) now I am trying to close the same overlay by calling dispose or remove but without much success. Can anyone advise on what I am doing wrong and the best way to close the over from a separate class?
Below is a snippet of my code (its quite long)
class RootApp extends StatefulWidget {
@override
RootAppState createState() => RootAppState();
}
class RootAppState extends State<RootApp> {
bool isFavorite = false;
int pageIndex = 0;
final FocusNode _focusNode = FocusNode();
PageController _pgController = PageController();
//For search
late OverlayState? overlayState;
late OverlayEntry overlayEntry;
void pgCont(pg){
print(pg);
if(_pgController.hasClients) {
_pgController.animateToPage(
pg, duration: Duration(milliseconds: 250), curve: Curves.bounceInOut);
}
print(_pgController.hasClients);
setState(() {
});
}
@override
Widget build(BuildContext context) {
final isPortrait = MediaQuery.of(context).orientation == Orientation.portrait;
return Scaffold(
extendBodyBehindAppBar: true,
body: PageView(controller: _pgController,
children: <Widget>[
getMovieBody(),
getTvBody(),
]),
bottomNavigationBar: getFooter(),
);
}
showOverlay(BuildContext){
final renderBox = context.findRenderObject() as RenderBox;
final searchOverlaySize = renderBox.size;
overlayState = Overlay.of(context);
overlayEntry = OverlayEntry(builder: (context)=>Positioned(
top: 0.0,
width: searchOverlaySize.width,
height: searchOverlaySize.height/3,
child: getSearchBox(),
),);
overlayState?.insert(overlayEntry);
}
void hideOverlay() {
print('trying to dispose');
// overlayEntry.remove(); //LateInitializationError: Field 'overlayEntry' has not been initialized.
// overlayEntry.dispose(); //LateInitializationError: Field 'overlayEntry' has not been initialized.
overlayState?.dispose(); // Error LateInitializationError: Field 'overlayState' has not been initialized.
overlayState = null;
}
I'm trying to use the following to call the hideOverlay from the class searchbox..
final RootAppState roots = new RootAppState();
roots.hideOverlay();
What Im I doing wrong or is there an easier way to call the destroy or remove the overlay? :(
Upvotes: 0
Views: 1642
Reputation: 2120
You should use GlobalKey
to fulfill your requirement.
// define globalKey where other class have access(eg. top level scope)
GlobalKey<DemoWidgetState> globalKey = GlobalKey();
// use globelKey in RootAppState
Scaffold(
key: globalKey
extendBodyBehindAppBar: true,
body: PageView(controller: _pgController, children: <Widget>[
getMovieBody(),
getTvBody(),
]),
bottomNavigationBar: getFooter(),
);
// call hideOverlay form other class
globalKey.currentState?.hideOverlay();
Upvotes: 1