简体   繁体   中英

How to open Drawer on clicking Icon inside an AppBar in Flutter?

I have my files as follows:

homepage.dart

return Scaffold{
      appBar: CustomAppBar(),
      drawer: CustomDrawer(),
}

CustomAppBar.dart

class HomePageAppBar extends StatelessWidget with PreferredSizeWidget {
return AppBar{
      leading: InkWell(
              onTap: () {
                // Need to open drawer when clicked
              },
              child: FaIcon(
                FontAwesomeIcons.bars,
                color: Theme.of(context).iconTheme.color,
                size: Theme.of(context).iconTheme.size,
              ),
            ),
}
@override
  Size get preferredSize => Size.fromHeight(kToolbarHeight);
}

CustomDrawer.dart

return Drawer{
}

Now since my AppBar and Drawer are in separate files, I cannot use Scaffold.of(context).openDrawer() to open the drawer. I tried setting a GlobalKey to my Drawer but was now able to access it from my CustomAppBar file.

I tried converting the CustomAppBar.dart file to a Scaffold so that it contains my appbar and my drawer and used Scaffold.of(context).openDrawer(). This caused the drawer to open and display only in the appbar area (Probably because of using PreferredSizeWidget).

How can I make the drawer open on clicking the AppBar's icon given that they are placed in separate files? I want to keep my AppBar and Drawer in separate files.

See the documentation https://api.flutter.dev/flutter/material/showModalBottomSheet.html

onPressed: () {
          showModalBottomSheet<void>(
            context: context,
            builder: (BuildContext context) {
              return Container(
                height: 200,
                color: Colors.amber,
                child: Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      const Text('Modal BottomSheet'),
                      ElevatedButton(
                        child: const Text('Close BottomSheet'),
                        onPressed: () => Navigator.pop(context),
                      )
                    ],
                  ),
                ),
              );
            },

Declare globalkey outside the class (Global) or create a static memeber

 GlobalKey<ScaffoldState> _globalkey = new GlobalKey<ScaffoldState>();

opend Drawer using globalkey.

 _globalkey.currentState?.openDrawer();

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM