'"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
  );    
}




Solution 1:[1]

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

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Aman Ali