Flutter如何让Container高度自适应ListView子项的高度?
解决方法
要实现Container自动适配所有子项高度且禁止ListView滚动,只需对ListView.builder做两处修改,同时移除Container的硬编码高度:
- 添加
shrinkWrap: true:让ListView根据子组件的总高度确定自身高度,不再依赖父容器的约束 - 添加
physics: const NeverScrollableScrollPhysics():禁用ListView自身的滚动功能,让外层的SingleChildScrollView接管整体滚动
修改后的完整代码如下:
Container( color: Colors.red, width: double.infinity, child: FutureBuilder( future: assesmentfuture, builder: (context, AsyncSnapshot<List<Assesment>> sn) { if (sn.hasData) { return ListView.builder( shrinkWrap: true, // 新增配置 physics: const NeverScrollableScrollPhysics(), // 新增配置 itemCount: sn.data!.length, itemBuilder: (context, index) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 10), child: Container( color: Colors.green, child: Text( sn.data![index].text, style: GoogleFonts.roboto( fontSize: 14, fontWeight: FontWeight.w400, ), textAlign: TextAlign.justify, ), ), ); }); } if (sn.hasError) { return const Center( child: Text("Error"), ); } return const Center( child: CircularProgressIndicator(), ); }), )
补充说明
shrinkWrap会让ListView遍历所有子组件计算高度,若子项数量极大可能影响性能,但普通场景下完全适用- 外层的
SingleChildScrollView已提供全局滚动能力,禁用ListView的滚动可避免滚动冲突
内容的提问来源于stack exchange,提问作者Md Zihad
相关产品推荐
相关产品推荐

