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

如何从showModalBottomSheet退出并跳转到指定页面?

Flutter Bottom Sheet关闭后跳转页面问题解决

点击Bottom Sheet中的容器时,期望先关闭Bottom Sheet再跳转到EventScreen页面,但实际操作后,新页面是在Bottom Sheet内部的路由栈中打开的,而非根页面之上。相关代码如下:

完整布局代码

Row(
  mainAxisAlignment: MainAxisAlignment.center,
  children: [
    InkWell(
      onTap: () {
        Navigator.pop(context);
        Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) => const EventScreen()),
        );
      },
      child: Container(
        height: 100,
        width: boxWidth,
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border.all(
            color: const Color.fromARGB(255, 122, 121, 121),
          ),
          borderRadius: const BorderRadius.all(
            Radius.circular(10),
          ),
        ),
        padding: const EdgeInsets.all(5.0),
        child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Icon(
                Icons.trending_up_rounded,
                size: 40,
                color: Colors.blue,
              ),
              Text(
                'Event Report',
                style: TextStyle(fontSize: fontSize),
              ),
            ]),
      ),
    ),
  ],
)

关键逻辑代码

InkWell(
  onTap: () {
    Navigator.pop(context);
    Navigator.push(
      context,
      MaterialPageRoute(
          builder: (context) => const EventScreen()),
    );
  },
)

解决方案

方案1:使用根导航器跳转

问题核心是Navigator.push使用的是Bottom Sheet的context,导致新页面被加入Bottom Sheet的子路由栈。改用根导航器的context即可解决:

InkWell(
  onTap: () {
    Navigator.pop(context); // 关闭Bottom Sheet
    // 获取根导航器执行跳转
    Navigator.of(context, rootNavigator: true).push(
      MaterialPageRoute(builder: (context) => const EventScreen()),
    );
  },
  // ... 容器代码
)

方案2:利用Bottom Sheet的返回Future处理跳转

如果Bottom Sheet是通过showModalBottomSheet打开的,可以监听它的返回值,在Bottom Sheet关闭后再执行跳转:

  1. 打开Bottom Sheet时添加回调:
showModalBottomSheet(
  context: context,
  builder: (context) => YourBottomSheetWidget(),
).then((result) {
  // 根据返回值判断是否跳转
  if (result == 'navigate_to_event') {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const EventScreen()),
    );
  }
});
  1. 修改Bottom Sheet内的点击逻辑:
InkWell(
  onTap: () {
    // 关闭时传递跳转标记
    Navigator.pop(context, 'navigate_to_event');
  },
  // ... 容器代码
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 13:04:55