如何从单独的 class 中处理或移除叠加层?

How to dispose or remove the overlay from a separate class?

请帮忙!

我已经从一个单独的 class 启动了叠加层(调用 showOverlay),现在我试图通过调用 dispose 或 remove 来关闭相同的叠加层,但收效甚微。任何人都可以建议我做错了什么以及从单独的 class 关闭结束的最佳方法吗?

下面是我的代码片段(很长)

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;
  }

我正在尝试使用以下方法从 class 搜索框调用 hideOverlay..

final RootAppState roots = new RootAppState();

roots.hideOverlay();

我做错了什么,或者有更简单的方法来调用销毁或删除叠加层吗? :(

您应该使用 GlobalKey 来满足您的要求。

// 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();