简体   繁体   中英

"How to open scaffold drawer from the custom AppBar ?"

I have made customized Drawer and AppBar . I want the Drawer to be opened when action widget in the AppBar is tapped. I want to know how to implement this for the custom 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
  );    
}


You should use GlobalKey in Scaffold , and call openEndDrawer method on it.

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

Update

GlobalKey<ScaffoldState> _key = GlobalKey();

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

Somewhere in some file.

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

Somewhere in some other file

buildProfileDrawer() {
  return Drawer();
}

You can use this in actions list:

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

We can use

Scaffold.of(context).openDrawer();

on onPressed inside an IconButton in your CustomAppBar or wherever you want to call the drawer.

In the Scaffold just ensure to provide the drawer: property a Drawer Widget.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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