簡體   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