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

Flutter:如何为modal_bottom_sheet包的模态框设置侧边间距

如何让modal_bottom_sheet的模态框两侧保留边距

问题场景

需要实现底部模态框与设备左右边缘存在间距,而非占满整个屏幕宽度,但使用modal_bottom_sheet包的showMaterialModalBottomSheet时,没有直接配置宽度的参数。尝试调整子Container的width属性无效,初期使用Padding包裹也未达到预期效果。

原问题代码(模态框占满全屏宽度)

Future<dynamic> preFocusModal(BuildContext context) {
  return showMaterialModalBottomSheet(
    context: context,
    builder: (context) => Container(
      height: 300,
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.secondary,
        borderRadius: BorderRadius.all(
          Radius.circular(10),
        ),
      ),
    ),
  );
}

解决方案

核心思路是将模态框的背景设为透明,再通过外层Padding控制边距:

  1. 给showMaterialModalBottomSheet添加backgroundColor: Colors.transparent,让模态框底层背景透明,露出屏幕背景
  2. 在builder返回的Widget外层包裹Padding,设置所需的边距值

最终实现代码

Future<dynamic> preFocusModal(BuildContext context) {
  return showMaterialModalBottomSheet(
    backgroundColor: Colors.transparent,
    context: context,
    builder: (context) => Padding(
      padding: EdgeInsets.all(15),
      child: Container(
        height: 400,
        decoration: BoxDecoration(
          color: Theme.of(context).colorScheme.secondary,
          borderRadius: BorderRadius.all(
            Radius.circular(30),
          ),
        ),
      ),
    ),
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 13:30:42