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

Flutter中实现Bottom Sheet高度自适应且最大为屏幕2/3的方法

解决方案

核心修改点

  • 移除对BottomSheet容器的固定高度设置,改用ConstrainedBox限制最大高度为屏幕的2/3,允许内容高度不足时自动收缩
  • 给Column添加mainAxisSize: MainAxisSize.min,让Column仅包裹自身内容而非占满父容器空间

修改后的代码

1. 打开BottomSheet的调用代码

Container(
  child: TextButton(
    onPressed: () {
      showModalBottomSheet(
        context: context,
        builder: (context) {
          double maxHeight = (2 / 3) * MediaQuery.of(context).size.height;
          // 用ConstrainedBox限制最大高度,不设置最小高度
          return ConstrainedBox(
            constraints: BoxConstraints(maxHeight: maxHeight),
            child: _BottomSheetWidget(),
          );
        },
        isScrollControlled: true,
      );
    },
    child: Text('Open Bottom Sheet'),
  ),
)

2. _BottomSheetWidget代码

class _BottomSheetWidget extends StatelessWidget {
  const _BottomSheetWidget();

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: SingleChildScrollView(
        child: Column(
          // 关键:让Column仅占用内容所需的最小高度
          mainAxisSize: MainAxisSize.min,
          children: [
            // 你的动态内容
          ],
        ),
      ),
    );
  }
}

原理说明

  • ConstrainedBox(maxHeight: maxHeight):确保BottomSheet的高度不会超过屏幕的2/3,当内容高度超过这个值时,会被限制在该高度内
  • SingleChildScrollView:在内容高度超过最大限制时,提供滚动能力
  • Column(mainAxisSize: MainAxisSize.min):让Column根据内部动态内容的高度自动调整,不会强制占满父容器的高度,解决内容不足时的空白问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 20:05:07