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

eni9jsuy  于 2023-01-28  发布在  其他
关注(0)|答案(3)|浏览(120)

我定制了DrawerAppBar,我希望AppBar中的action widget被点击时,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
  );    
}
e4yzc0pl

e4yzc0pl1#

应该在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();
}
mutmk8jj

mutmk8jj2#

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

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

np8igboo3#

我们可以用
Scaffold.of(context).openDrawer();
on on在CustomAppBar中的IconButton内或您要调用抽屉的任何位置按下。
在Scaffold中,只需确保为抽屉小部件提供drawer:属性。

相关问题