Flutter: How to open Drawer programmatically

Null safe code

  • Using GlobalKey:

    final GlobalKey<ScaffoldState> _key = GlobalKey(); // Create a key
    
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        key: _key, // Assign the key to Scaffold.
        drawer: Drawer(),
        floatingActionButton: FloatingActionButton(
          onPressed: () => _key.currentState!.openDrawer(), // <-- Opens drawer
        ),
      );
    }
    
  • Using Builder:

    @override
    Widget build(BuildContext context) {
      return Scaffold(
        drawer: Drawer(),
        floatingActionButton: Builder(builder: (context) {
          return FloatingActionButton(
            onPressed: () => Scaffold.of(context).openDrawer(), // <-- Opens drawer.
          );
        }),
      );
    }
    

If you want to disable opening the Drawer using a drag gesture, you can set

Scaffold(
  drawerEnableOpenDragGesture: false
  // above code ...
)

Leave a Comment