flutterflutter-layoutflutter-webflutter-animationflutter-test

Flutter, How To make Button to open drawer in Flutter


I trying make a button for open my drawer, but i can't, this my first time using flutter

my running ui

Flutter UI

  return Scaffold(

  drawer: Drawer(),
  body: Column(
    children: <Widget>[
      ClipPath(
        clipper: MyClipper(),
        child: Container(
          height: 350,
          width: double.infinity,
          decoration: BoxDecoration(
            gradient: LinearGradient(
                begin: Alignment.topRight,
                end: Alignment.bottomLeft,
                colors: [
                  Color(0xFF3383CD),
                  Color(0xFF11429F),
                ]),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              const SizedBox(height: 12),
              IconButton(
                icon: const Icon(
                  Icons.add, size: 18,
                  color: Colors.white,
                  ),
                onPressed: () {
                  Scaffold.of(context).openDrawer();
                },
              ),

Solution

  • The best way to do this is using GlobalKey.

    1. Define a GlobalKey for ScaffoldState for your widget.

      GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();

    2. Assign this key to the Scaffold.

    Scaffold( key: scaffoldKey, ....)

    1. Call Opendrawer using this key from the button's onPressed call.

    FlatButton(onPressed: () { scaffoldKey.currentState.openDrawer(); })