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

Flutter Bottom Sheet Dialog 部分场景下键盘弹出时resize异常如何解决

问题根因

两种打开方式使用的context层级不同,Tab页内的context获取到的MediaQuery.viewInsets不是弹窗所在层级的最新键盘高度,导致底部偏移计算错误。

修正方案

调整点

  1. 调整MediaQuery使用的上下文:弹窗builder内不要使用外层调用showModalBottomSheet的上下文,要使用builder回调返回的弹窗自身上下文
  2. 新增useRootNavigator: true配置:让showModalBottomSheet统一挂载在根导航层,避免不同页面上下文的视图参数差异
  3. 可选兜底:如果你的项目存在嵌套Scaffold,可统一用根Scaffold的GlobalKey获取的上下文调用showModalBottomSheet

修正后核心代码

showModalBottomSheet(
    backgroundColor: foreground_color,
    isScrollControlled: true,
    useRootNavigator: true, // 新增配置项
    shape: RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(20.r))),
    context: context,
    builder: (sheetContext) { // 重命名参数避免和外层context混淆
      return AnimatedPadding(
        duration: const Duration(milliseconds: 250),
        curve: Curves.easeInOutSine,
        // 替换为弹窗自身的上下文获取键盘高度
        padding: EdgeInsets.only(bottom: MediaQuery.of(sheetContext).viewInsets.bottom),
        child: SafeArea(
          maintainBottomViewPadding: true,
          child: Wrap(
            children: [
              Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 原有弹窗内容保持不变
                ],
              )
            ],
          ),
        ),
      );
    }
);

补充适配

如果调整后仍存在偏移,可做以下修改:

  • 把SafeArea的maintainBottomViewPadding改为false,或者直接移除SafeArea组件
  • 弹窗内容外层嵌套SingleChildScrollView,避免键盘弹出后内容高度溢出

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 07:06:04