You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SliverAppBar内添加Drawer无编译错误但运行后无法显示问题

问题原因
  • 你在IconButton的onPressed回调里仅声明了一个Drawer实例,没有执行任何弹出Drawer的系统方法,这个声明的对象也没有关联到当前页面的Scaffold,自然不会触发弹出逻辑。
  • Flutter原生Drawer组件需要先挂载到当前页面Scaffold的drawer(左侧滑入)或endDrawer(右侧滑入)属性上,再通过对应API触发弹出。
修复步骤
  1. 首先把你写的Drawer组件移到当前页面Scaffold的endDrawer属性中(你的菜单按钮放在AppBar的actions右侧区域,用endDrawer更符合交互习惯),同时修改onPressed逻辑:
// 你的页面Scaffold结构示例
Scaffold(
  // 新增这部分,把Drawer放到Scaffold的属性下
  endDrawer: Drawer(
    child: Center(
      child: Text('This is Drawer'),
    ),
  ),
  body: CustomScrollView(
    // 你原来的CustomScrollView代码无需修改
    slivers: <Widget>[
      SliverLayoutBuilder(
        builder: (BuildContext context, constraints) {
          final scrolled = constraints.scrollOffset > 50;
          final scrolledicon = constraints.scrollOffset > 0;

          return SliverAppBar(
            expandedHeight: 20,
            toolbarHeight: 65,
            leading: Padding(
              padding: const EdgeInsets.only(top: 2),
              child: Icon(DBIcons.logo, color: Colors.red, size: 50),
            ),
            actions: [
              Padding(
                padding: const EdgeInsets.all(10),
                child: IconButton(
                  icon: Icon(Icons.menu),
                  color: scrolledicon ? Colors.white : Colors.black,
                  // 修改onPressed的逻辑
                  onPressed: (){
                    // 调用系统API弹出右侧endDrawer
                    Scaffold.of(context).openEndDrawer();
                  },
                ),
              ),
            ],
            backgroundColor: scrolled ? Colors.black : Colors.transparent,
            elevation: 0,
            pinned: true,
          );
        },
      ),
    ],
  )
)
  1. 如果调用Scaffold.of(context)时提示找不到对应Scaffold上下文,可以用Builder包裹IconButton,或者使用GlobalKey定位Scaffold:
// 先在State类中定义GlobalKey
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

// 绑定到Scaffold上
Scaffold(
  key: _scaffoldKey,
  endDrawer: const Drawer(child: Center(child: Text('This is Drawer'))),
  // 其余代码不变
)

// onPressed里改为通过key调用
onPressed: (){
  _scaffoldKey.currentState?.openEndDrawer();
}
额外说明
  • 如果需要左侧弹出Drawer,只需把endDrawer改为drawer属性,调用方法替换为openDrawer()即可。
  • 不需要自定义菜单按钮也能触发Drawer:当你给Scaffold设置了drawer属性后,SliverAppBar会自动在leading位置生成汉堡菜单按钮,点击就能直接弹出左侧Drawer。

内容的提问来源于stack exchange,提问作者ezra Rahardian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 01:54:07