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

嵌套父ListView的两个ListView Builder无法复用,一次性全渲染求助

Flutter嵌套列表组件复用问题解决

问题原因

你当前的嵌套ListView写法中,子ListView设置了shrinkWrap: true,这个属性会强制子ListView一次性计算并渲染所有200个RecCell——因为它需要确定自身总高度来适配父ListView,直接导致ListView.builder的组件复用机制失效。

解决方案:使用CustomScrollView + SliverList

将父ListView替换为CustomScrollView,把两个子ListView.builder改成SliverList,让所有列表项处于同一个滚动上下文,实现按需渲染和组件复用。

修改后的完整代码如下:

主页面build方法

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: CustomScrollView(
      slivers: <Widget>[
        _firstSliverList(),
        _secondSliverList(),
      ],
    ),
  );
}

第一个列表组件(绿色背景)

Widget _firstSliverList() {
  return SliverList(
    delegate: SliverChildBuilderDelegate(
      (context, index) => Container(
        color: Colors.green,
        child: RecCell(index: index),
      ),
      childCount: 200,
    ),
  );
}

第二个列表组件(红色背景)

Widget _secondSliverList() {
  return SliverList(
    delegate: SliverChildBuilderDelegate(
      (context, index) => Container(
        color: Colors.red,
        child: ListTile(title: Text("Second $index")),
      ),
      childCount: 200,
    ),
  );
}

原理说明

CustomScrollView整合多个Sliver组件到统一的滚动体系中,会根据当前滚动位置按需创建和回收列表项,完全发挥组件复用的优势。同时移除了shrinkWrap属性,避免强制计算所有子项高度,让滚动视图自然管理组件生命周期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 02:06:30