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

Flutter中showModalBottomSheet内嵌GridView.builder报错求助

解决Flutter BottomSheet中GridView的布局错误

问题原因

  • 垂直空间无约束:Column是垂直方向的无边界容器,即便给GridView设置了shrinkWrap: true,它在Column里还是会试图占用无限高度,触发"Vertical viewport was given unbounded height"错误。
  • 缺少列表长度限制:GridView.builder未指定itemCount,会无限生成子组件,直接导致RenderBox无法完成布局,引发第二个错误。

修复步骤

  1. 用Expanded包裹GridView:让GridView占据Column中除顶部标题栏外的剩余垂直空间,给它明确的高度约束。
  2. 添加itemCount属性:必须指定列表的总长度,避免无限构建子组件。
  3. 优化交互(可选):给关闭按钮添加Navigator.pop(context),让用户能正常关闭BottomSheet。

修复后的完整代码

GestureDetector(
  onTap: () {
    showModalBottomSheet(
      context: context,
      // 可选:开启后BottomSheet可占满更多屏幕高度,适合内容较多的场景
      // isScrollControlled: true,
      builder: (BuildContext context) {
        return SizedBox(
          // 可选:手动限制BottomSheet的最大高度
          // height: MediaQuery.of(context).size.height * 0.8,
          child: Column(
            children: [
              Row(
                children: [
                  IconButton(
                    onPressed: () => Navigator.pop(context),
                    icon: Image.asset('assets/icons/x.png'),
                  ),
                  const SizedBox(width: 100),
                  const Text(
                    'Categories',
                    style: AppTextStyles.style16w600,
                  ),
                ],
              ),
              // 关键:用Expanded给GridView分配剩余空间
              Expanded(
                child: GridView.builder(
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 1,
                  ),
                  shrinkWrap: true,
                  // 必须设置itemCount,指定列表项数量
                  itemCount: 10,
                  itemBuilder: (context, index) {
                    return Container(
                      height: 100,
                      child: Text('hoi $index'),
                    );
                  },
                ),
              ),
            ],
          ),
        );
      },
    );
  },
)

额外建议

如果你的crossAxisCount:1只是想实现列表布局,更推荐用ListView.builder,比GridView更轻量化,也能避免不必要的布局计算。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 11:46:28