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

Flutter中showModalBottomSheet的SafeArea失效问题及解决方法

Flutter中SafeArea适配showModalBottomSheet的问题解决

问题描述

SafeArea无法正确包裹showModalBottomSheet,需要让弹窗显示在状态栏下方。
问题截图

初始实现代码:

class ModalBottomSheet {
  static void renderModalBottomSheet(BuildContext context, Widget widget) {
    showModalBottomSheet(
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(
          top: Radius.circular(border2),
        ),
      ),
      context: context,
      builder: (BuildContext context) {
        return SafeArea(
          child: Container(
            padding: EdgeInsets.only(
              bottom: MediaQuery.of(context).viewInsets.bottom,
            ),
            child: widget,
          ),
        );
      },
    );
  }
}

尝试过以下方案但未解决:

MediaQuery.of(context).padding.top

MediaQueryData.fromWindow(WidgetsBinding.instance.window).padding.top

解决方法

通过以下两步解决问题:

  1. 给showModalBottomSheet添加透明背景:
backgroundColor: Colors.transparent,
  1. 给内容设置顶部内边距,适配状态栏高度:
top: MediaQuery.of(context).padding.top,

完整代码

class ModalBottomSheet {
  static void renderModalBottomSheet(BuildContext context, Widget widget) {
    showModalBottomSheet(
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      context: context,
      builder: (_) {
        return SafeArea(
          child: Padding(
            padding: EdgeInsets.only(
              top: MediaQuery.of(context).padding.top,
              bottom: MediaQuery.of(context).viewInsets.bottom,
            ),
            child: widget,
          ),
        );
      },
    );
  }
}

注:弹窗的圆角、背景色等样式可以直接设置在传入的子Widget中。

效果展示

  • 键盘展开状态:键盘展开
  • 键盘收起状态:键盘收起

内容的提问来源于stack exchange,提问作者Marlon Parra Ruiz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 22:18:20