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

如何在SimpleDialog中显示ListView.builder?代码问题求助

在SimpleDialog中使用ListView.builder失效的解决办法

问题核心在于ListView.builder需要明确的尺寸约束,而SimpleDialog的children容器默认没有给子组件限制高度,导致ListView无法正确计算自身尺寸,进而无法正常渲染。

你可以通过两种方式解决:

方式一:给ListView指定固定高度

用Container或SizedBox包裹ListView,设置合适的固定高度:

onTap: () {
  return showDialog(
    builder: (BuildContext context) {
      return SimpleDialog(
        title: Text('names'),
        children: [
          Container(
            height: 300, // 根据需求调整高度
            child: ListView.builder(
              itemCount: names.length,
              itemBuilder: ((context, index) {
                return SimpleDialogOption(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text(names[index].name),
                );
              })
            ),
          )
        ],
      );
    },
    context: context);
},

方式二:使用shrinkWrap自适应高度

开启shrinkWrap: true让ListView根据内容高度自适应,同时禁用内部滚动避免与Dialog的滚动冲突:

onTap: () {
  return showDialog(
    builder: (BuildContext context) {
      return SimpleDialog(
        title: Text('names'),
        children: [
          ListView.builder(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(), // 禁用内部滚动,使用Dialog的滚动逻辑
            itemCount: names.length,
            itemBuilder: ((context, index) {
              return SimpleDialogOption(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: Text(names[index].name),
              );
            })
          )
        ],
      );
    },
    context: context);
},

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:35:22