Home > Software design >  How to add Drawer without AppBar by clicking on the icon Flutter
How to add Drawer without AppBar by clicking on the icon Flutter

Time:04-27

I'm using extendBodyBehindAppBar and creating an AppBar by extending PreferredSizeWidget. I have a burgerMenu (buttonIcon) icon in appBar file that needs to be clicked to open the Drawer. Tell me how to correctly implement the opening of the Drawer in my case, without using the standard version with the AppBar?

home

Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: LogoAppBar(buttonIcon: SvgPicture.asset(constants.Assets.burgerMenu)),
      body: const HomeBody(),
    );
  }

appBar

class LogoAppBar extends StatelessWidget with PreferredSizeWidget {
  LogoAppBar({Key? key, required this.buttonIcon, this.onPressed})
      : super(key: key);

  final SvgPicture buttonIcon;
  final Function()? onPressed;

  @override
  Widget build(BuildContext context) {
    SvgPicture logoSvg = SvgPicture.asset(
        '...logo.svg',
        height: 40);

    double horizontalPadding = 24;

    return SafeArea(
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: horizontalPadding),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                logoWidget(logoSvg, horizontalPadding),
                SizedBox(child: buttonIcon),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget logoWidget(SvgPicture logoSvg, double horPadding) {
    return Align(
      alignment: Alignment.centerLeft,
      child: logoSvg,
    );
  }

  @override
  Size get preferredSize => const Size.fromHeight(60);
}

CodePudding user response:

You can use GlobalKey to open the drawer and open using myScaffoldKey.currentState?.openDrawer();.

Make sure to wrap you buttonIcon with tappable widget like GestureDetector/InkWell and add onPressed.

  final GlobalKey<ScaffoldState> _sKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _sKey ,
      appBar: LogoAppBar(
        onPressed: () {
          debugPrint("open");
          _sKey.currentState?.openDrawer();
        },
      ),
      drawer: const Drawer(),
      extendBodyBehindAppBar: true,
      //...
  • Related