Flutter - Is there a way to use just IconButton (without creating an app bar) to open the drawer?

心不动则不痛 提交于 2021-02-19 05:46:25

问题


I'm trying to use the IconButton that can open the drawer on my app page, so when I tap the icon button, I expect to see the drawer. I've been looking up a way to do so online, but seemed like there're only two solutions: I can either use the appbar to put the IconButton in, or I can try the floating action button. But they're not what I'm looking for, I want just the IconButton to open the drawer. Is it possible do it?


回答1:


Yes, you can easily open the drawer through IconButton without using appBar. You need to use Key like I had used _scaffoldKey and use _scaffoldKey.currentState.openDrawer() method to open the drawer in IconButton widget.

class HomeState extends StatelessWidget {

final GlobalKey<ScaffoldState> _scaffoldKey =  GlobalKey<ScaffoldState>();

 @override
Widget build(BuildContext context) {

return Scaffold(
  key: _scaffoldKey,
         drawer: Drawer(
      child: ListView(
        children: <Widget>[
          ListTile(
            title: Text("Ttem 1"),
            trailing: Icon(Icons.arrow_forward),
          ),
          ListTile(
            title: Text("Item 2"),
            trailing: Icon(Icons.arrow_forward),
          ),
        ],
      ),
    ),
        body: ListView(
         children:[

    Container(
              margin: EdgeInsets.only(left: 15.0,top:100.0),
              child: IconButton(
                icon: Icon(Icons.menu),
                onPressed: () {
                  _scaffoldKey.currentState.openDrawer();
                },

              ),
            ),
            ]
        ),
            );}


   }


来源:https://stackoverflow.com/questions/55697939/flutter-is-there-a-way-to-use-just-iconbutton-without-creating-an-app-bar-to

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!