Flutter 如何通过点击图标添加没有 AppBar 的 Drawer

How to add Drawer without AppBar by clicking on the icon Flutter

我正在使用 extendBodyBehindAppBar 并通过扩展 PreferredSizeWidget 创建一个 AppBar。我在 appBar 文件中有一个 burgerMenu (buttonIcon) 图标,需要单击它才能打开 Drawer。告诉我如何在我的案例中正确实现 Drawer 的开头,而不使用带有 AppBar?

的标准版本

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);
}

您可以使用GlobalKey打开抽屉并使用 myScaffoldKey.currentState?.openDrawer();打开。

确保用 GestureDetector/InkWell 等可点击小部件包裹 buttonIcon 并添加 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,
      //...