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

BottomSheet内嵌Navigator后全屏显示,求内容自适应高度解决方案

解决BottomSheet中使用Navigator导致全屏的问题

问题原因

Navigator组件默认会占据父级提供的全部可用空间,再加上你开启了isScrollControlled: true,showModalBottomSheet会给子组件分配全屏的可用空间,最终导致BottomSheet被拉伸至全屏。

解决方案

通过Wrap组件包裹Navigator,让Wrap根据内部内容的实际高度自动调整自身尺寸,从而让BottomSheet恢复自适应高度的行为。如果需要限制BottomSheet的最大高度,可以搭配ConstrainedBox一起使用。

修改后的完整代码

await showModalBottomSheet<void>(
  isDismissible: true,
  useSafeArea: true,
  isScrollControlled: true,
  backgroundColor: Colors.transparent,
  context: blocContext,
  builder: (BuildContext context) {
    // 使用Wrap包裹Navigator,限制其高度为内容实际高度
    return Wrap(
      children: [
        Navigator(
          onGenerateRoute: (context) => MaterialPageRoute<ModalRoute>(
            fullscreenDialog: false,
            builder: (context) => Container(
              color: Colors.white,
              child: Stack(
                fit: StackFit.loose,
                children: [
                  CustomScrollView(
                    shrinkWrap: true,
                    slivers: [
                      SliverToBoxAdapter(
                        child: Container(
                          height: 50,
                          width: 50,
                          color: Colors.yellow,
                        ),
                      ),
                      SliverList.separated(
                        itemCount: 5,
                        itemBuilder: (context, index) {
                          return Container(
                            height: 30,
                            color: Colors.green,
                          );
                        },
                        separatorBuilder: (context, index) {
                          return gapH20;
                        },
                      ),
                    ],
                  )
                ],
              ),
            ),
          ),
        ),
      ],
    );
  },
);

可选优化:限制最大高度

如果希望BottomSheet不会超过屏幕的一定比例(比如70%),可以用ConstrainedBox包裹Wrap:

return ConstrainedBox(
  constraints: BoxConstraints(
    maxHeight: MediaQuery.of(context).size.height * 0.7,
  ),
  child: Wrap(
    children: [
      // Navigator代码不变
    ],
  ),
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 22:30:04