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

添加ListView.builder后Flutter应用栈溢出崩溃问题求助

Flutter添加ListView.builder后栈溢出崩溃解决方案

核心根因

栈溢出报错本质是程序出现了无限递归的函数调用,你这个场景下90%的概率出自CartItem组件的实现逻辑,和CartScreen本身的ListView写法关联不大。

排查&解决步骤

  • 检查cart_item.dart文件实现:
    1. 禁止在CartItem的build方法中调用会修改Cart、Orders等Provider状态的方法,这类方法会触发notifyListeners,导致整个CartScreen反复重建,ListView无限重新渲染子项形成死循环
    2. 确认CartItem内部没有嵌套未加高度约束的ListView、GridView等滚动组件,如果确实需要嵌套滚动组件,必须给嵌套的滚动组件添加固定高度,或者配置shrinkWrap: true、physics: NeverScrollableScrollPhysics()
    3. 可以先给CartItem外层套一个固定高度的SizedBox做测试,例如SizedBox(height: 100, child: 原CartItem内容),如果不再崩溃说明是子项高度无约束导致布局计算无限递归
  • 优化CartScreen中ListView.builder的冗余逻辑
    你当前的itemBuilder里反复调用toList()会生成多个冗余数组,虽然不会直接导致崩溃,但也可以优化避免潜在的性能问题,修改后的代码如下:
Expanded(
  child: ListView.builder(
    itemBuilder: (ctx, i) {
      final cartItemList = cart.items.values.toList();
      final cartKeyList = cart.items.keys.toList();
      return CartItem(
        cartItemList[i].id,
        cartKeyList[i],
        cartItemList[i].price,
        cartItemList[i].quantity,
        cartItemList[i].title,
      );
    },
    itemCount: cart.items.length,
  ),
)
  • 极简复现排查
    如果以上操作都没有解决问题,可以临时把CartItem的内容替换成最简布局测试:
itemBuilder: (ctx, i) => Container(
  height: 50,
  color: Colors.red,
  child: Text(cart.items.values.toList()[i].title),
)

如果替换后不再崩溃,就能100%确认问题出自CartItem的内部实现,逐行注释CartItem代码定位问题即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 17:24:01