ListView.builder嵌套SingleChildScrollView报Vertical viewport unbounded height错误
解决SingleChildScrollView嵌套ListView.builder的"Vertical viewport was given unbounded height"错误
错误原因
ListView默认会尝试占满父组件的全部可用垂直空间,但SingleChildScrollView本身没有固定高度,它的高度由子内容决定——这就导致ListView拿到的是无限高度,直接触发错误。就算给ListView套了固定高度的Container,如果外层布局(比如Column)没有约束高度,Container的设置也不会生效。
解决方案
分两种场景处理:
场景1:需要整体滚动(ListView上方还有其他组件)
给ListView.builder添加两个关键参数:
shrinkWrap: true:让ListView根据子项实际高度自适应,不再强行占满空间physics: NeverScrollableScrollPhysics():禁用ListView自身的滚动逻辑,交给外层SingleChildScrollView统一处理
修改后的完整代码:
return SingleChildScrollView( child: ListView.builder( shrinkWrap: true, physics: NeverScrollableScrollPhysics(), scrollDirection: Axis.vertical, itemCount: dailyUpdate!.forecast!.forecastday!.length, itemBuilder: (context, index) { return Card( elevation: 3, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10)), color: Color.fromARGB(255, 65, 65, 64), child: Padding( padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 5), child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Container( width: 50, child: Image.network( 'https:' + dailyUpdate!.forecast!.forecastday![index].day! .condition!.icon .toString(), width: 50, ), ), Container( width: 85, child: customText( DateFormat('EEE, MMMM d').format(DateTime.parse( dailyUpdate.forecast!.forecastday![index].date .toString())), color: Colors.white), ), Container( width: 120, child: customText( dailyUpdate.forecast!.forecastday![index].day! .condition!.text .toString(), color: Colors.white), ), Container( width: 60, child: customText( dailyUpdate.forecast!.forecastday![index].day! .maxtempC! .round() .toString() + ' / ' + dailyUpdate.forecast!.forecastday![index].day! .mintempC! .round() .toString(), color: Colors.white), ), ], ), ), ); }, ), );
场景2:ListView是页面唯一滚动组件
直接移除SingleChildScrollView即可——ListView本身自带滚动功能,不需要额外包裹,这样也能避免高度无限的问题。
额外提醒
如果你的ListView是放在Column组件内,不管有没有SingleChildScrollView,都需要用Expanded或Flexible包裹ListView,让Column为它分配可用高度,否则同样会触发相同错误。示例:
Column( children: [ // 页面其他固定高度组件 Expanded( child: ListView.builder( // 你的ListView代码 ), ), ], )
内容的提问来源于stack exchange,提问作者Mr. Anonymous
相关产品推荐
相关产品推荐

