繁体   English   中英

“如何从自定义 AppBar 打开脚手架抽屉?”

[英]"How to open scaffold drawer from the custom AppBar ?"

我已经定制了DrawerAppBar 我希望在AppBar中的动作小部件被点击时打开Drawer 我想知道如何为自定义AppBar实现这个

@override
 Widget build(BuildContext context) {
  return Scaffold(
   endDrawer:buildProfileDrawer(),
   appBar: setAppBar(),
   body: HomeBody()
  );
}

//custom widget
Widget setAppBar(){
  return AppBar(
    actions: <Widget>[
      IconButton(
        icon: Icon(Icons.account_circle,),
        onPressed: () {
          //Open the drawer
        },
      )
    ],
  );
}

//Custom drawer
buildProfileDrawer() {
  return Drawer(
    //....drawer childs
  );    
}


您应该在Scaffold使用GlobalKey ,并对其调用openEndDrawer方法。

GlobalKey<ScaffoldState> _key = GlobalKey(); // add this

@override
Widget build(BuildContext context) {
  return Scaffold(
    key: _key, // set it here
    endDrawer: buildProfileDrawer(),
    appBar: setAppBar(),
    body: Center(),
  );
}

//custom widget
Widget setAppBar() {
  return AppBar(
    actions: <Widget>[
      IconButton(
        icon: Icon(Icons.account_circle),
        onPressed: () {
          _key.currentState.openEndDrawer(); // this opens drawer
        },
      )
    ],
  );
}

//Custom drawer
buildProfileDrawer() {
  return Drawer();
}

更新资料

GlobalKey<ScaffoldState> _key = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _key,
      endDrawer: buildProfileDrawer(),
      appBar: setAppBar(_key),
      body: Center(),
    );
  }

文件中的某处。

Widget setAppBar(GlobalKey<ScaffoldState> globalKey) {
  return AppBar(
    actions: <Widget>[
      IconButton(
        icon: Icon(Icons.account_circle),
        onPressed: () {
          globalKey.currentState.openEndDrawer();
        },
      )
    ],
  );
}

其他文件中的某处

buildProfileDrawer() {
  return Drawer();
}

您可以在操作列表中使用它:

 StatefulBuilder(
            builder: (BuildContext context, setState) {
              return IconButton(
                icon: Icon(Icons.format_align_right),
                onPressed: () {
                  Scaffold.of(context).openEndDrawer();
                },
              );
            },
          ),

我们可以用

Scaffold.of(context).openDrawer();

在您的 CustomAppBar 中的 IconButton 内的 onPressed 上或您想要调用抽屉的任何地方。

在 Scaffold 中,只需确保提供drawer:属性一个 Drawer Widget。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM