Flutter 从不同的有状态小部件打开抽屉菜单

Flutter 从不同的有状态小部件打开抽屉菜单,flutter,dart,Flutter,Dart,我有3个StatefulWidget,MainPage,CustomAppbar和ProfileCustomAppbar。在我的主页中,我按如下方式填充我的抽屉: Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: (currentPage == profilePage) ? ProfileCustomAppbar(

我有3个StatefulWidget,MainPage,CustomAppbar和ProfileCustomAppbar。在我的主页中,我按如下方式填充我的抽屉:

    Widget build(BuildContext context) {
    return MaterialApp(

      home: Scaffold(
        appBar: (currentPage == profilePage)

            ? ProfileCustomAppbar(
                height: 60,
              )
            : CustomAppbar(
                height: 60,
              ),
        endDrawer: populateDrawer(),
        body: Container(
          decoration: BoxDecoration(color: Colors.white),
          child: currentPage,
        ),

      ),
    );
  }
      populateDrawer() {
        return Theme(
          data: Theme.of(context).copyWith(
              canvasColor:
              Colors.white //This will change the drawer background to blue.
            //other styles
          ),
          child: Drawer(
            child: Column(
              children: <Widget>[
                DrawerHeader(
                  child: Center(
                    child: Image.asset("assets/images/lf_logo.png",
                        height: 100, width: 100),
                  ),
                ),
                Divider(color: Configuration.PrimaryColor),

              ],
            ),
          ),
        );
      }

但是抽屉没有打开,我如何修复它?

您需要将IconButton小部件包装在Builder小部件中以打开抽屉。请参阅以下代码:

      Builder(
        builder: (BuildContext context) {
          return new IconButton(
            icon: Icon(Icons.category),
            onPressed: () {
              Scaffold.of(context).openDrawer();
            },
          );
        },
      ),

为脚手架使用一个键,然后使用该键获取正确的上下文

  GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
...
这就是我修复它的方法

首先,我在父窗口小部件中创建新函数

  openTheDrawer(){
    _scaffoldKey.currentState.openEndDrawer();
  }
然后我调用了另一个statefull小部件中的函数

 widget.parent.openTheDrawer();

您可以创建一个回调函数,该函数将调用
\u scaffoldKey.currentState.openEndDrawer()

在脚手架钥匙所属的位置。然后,将回调函数传递到要调用它的位置。

Hi,我得到了这个错误
i/flatter(18574):引发了另一个异常:NoSuchMethodError:方法“openDrawer”在null上被调用我得到的小部件未定义
  openTheDrawer(){
    _scaffoldKey.currentState.openEndDrawer();
  }
 widget.parent.openTheDrawer();