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

在ListView.builder中使用Expanded组件报"Incorrect use of ParentDataWidget"错误

问题解决:ListView.builder中Container自适应文本尺寸并修复Expanded错误

错误原因

Expanded是专门为Flex布局组件(如Row、Column)设计的ParentDataWidget,用于在Flex容器内分配剩余空间。但ListView.builder的item并非Flex的直接子节点,直接在itemBuilder中返回Expanded,就会触发"Incorrect use of ParentDataWidget"错误。

解决方案

要让Container根据Text内容自动调整大小,完全不需要Expanded,直接移除该组件即可。ListView的item默认会根据子组件的尺寸自适应高度,而Text组件默认softWrap: true,会自动换行显示长文本,刚好满足需求。

修改后的完整代码:

List<String> values = [
    "short text",
    "long textlong textlong textlong textlong textlong textlong textlong textlong textlong textlong textlong textlong textlong textlong textlong textlong textlong text"
  ];
body: ListView.builder(
      shrinkWrap: true,
      itemCount: values.length,
      itemBuilder: (context, index) {
        return Container(
            margin: EdgeInsets.all(10),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(20),
              boxShadow: const [
                BoxShadow(
                  color: Colors.grey,
                  blurRadius: 2.0,
                  spreadRadius: 0.0,
                  offset: Offset(2.0, 2.0),
                ),
              ],
            ),
            child: Padding(
              // 给文本添加内边距,避免贴住容器边缘
              padding: EdgeInsets.all(12),
              child: Text(values[index]),
            ));
      }),

额外优化建议

  • 如果需要限制容器最大宽度(避免长文本撑满屏幕),可以给Container添加约束:constraints: BoxConstraints(maxWidth: 320)
  • 若要让容器居中显示,可在外层包裹Align(child: Container(...))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 16:55:27