Flutter: How to open Drawer programmatically

你离开我真会死。 提交于 2020-03-13 06:34:09

问题


I want to open Drawer programmatically not by sliding it, how to disable that sliding functionality (touch functionality of Drawer)


回答1:


Hacky but it works. To disable the slide to open functionality you can set the property drawerEdgeDragWidth on Scaffold to 0.

@override
Widget build(BuildContext context) {
  return Scaffold(
    drawerEdgeDragWidth: 0, // THIS WAY IT WILL NOT OPEN
    drawer: Drawer(),
    appBar: AppBar(
      leading: IconButton(
        icon: Icon(Icons.menu),
        onPressed: () {
          Scaffold.of(context).openDrawer();
        },
      ),
    ),
  );
}



回答2:


Output:

You'll need to create a GlobalKey and use openDrawer() method on it.

GlobalKey<ScaffoldState> _drawerKey = GlobalKey();
bool enabled = false; // tracks if drawer should be opened or not

@override
Widget build(BuildContext context) {
  return Scaffold(
    key: _drawerKey, // assign key to Scaffold
    drawer: Drawer(),
    appBar: AppBar(
      leading: IconButton(
        icon: Icon(Icons.menu),
        onPressed: () {
          if (enabled) {
            // open drawer if this value is true
            _drawerKey.currentState.openDrawer();
          }
        },
      ),
    ),
  );
}

Whenever you need to open the drawer simply use

_drawerKey.currentState.openDrawer();



回答3:


appBar: AppBar(

      automaticallyImplyLeading: false,
      title: Text(
        "Infilon Technologies",
        style:
            TextStyle(fontFamily: "Poppins", fontWeight: FontWeight.w600),
      ),
      actions: <Widget>[
        IconButton(
          icon: Icon(Icons.menu),
          onPressed: () {
            if (_scaffoldKey.currentState.isEndDrawerOpen) {
              _scaffoldKey.currentState.openDrawer();
            } else {
              _scaffoldKey.currentState.openEndDrawer();
            }
          },
        ),
      ],
    ),


来源:https://stackoverflow.com/questions/57748170/flutter-how-to-open-drawer-programmatically

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