Flutter中ListView在Column正常,置于Row报错如何解决?
Row中嵌套ListView.builder布局错误修复
问题原因
Row是水平方向的弹性布局容器,会给子组件提供无限的水平约束空间。而你设置了shrinkWrap: true的ListView.builder,需要基于有界宽度来计算自身布局尺寸,无法处理无界的水平约束,因此触发了constraints.hasBoundedWidth断言错误。换成Column能正常运行,是因为Column在垂直方向由外层SingleChildScrollView提供了有界约束,ListView的垂直布局可以正常计算。
修复方案
有两种常用解决方式:
方案1:给ListView指定固定宽度
通过SizedBox或容器给ListView设置明确宽度,让它在Row中获得有界水平约束:
Scaffold( body: SafeArea( child: SingleChildScrollView( scrollDirection: Axis.vertical, child: Row( mainAxisSize: MainAxisSize.max, children: [ SizedBox( width: 200, // 根据需求调整宽度 child: ListView.builder( shrinkWrap: true, itemCount: rideInfo[0]['matched'][0]['companionInfo'].length, itemBuilder: (context, index) { return Container( color: Colors.red, height: 40, width: 40, child: const Text("Test"), ); }, ), ), ], ), ), ), )
方案2:用Expanded让ListView占据Row剩余空间
如果希望ListView自动填充Row的剩余水平空间,用Expanded包裹它,Expanded会把Row的剩余空间作为有界约束传递给ListView:
Scaffold( body: SafeArea( child: SingleChildScrollView( scrollDirection: Axis.vertical, child: Row( mainAxisSize: MainAxisSize.max, children: [ Expanded( child: ListView.builder( shrinkWrap: true, itemCount: rideInfo[0]['matched'][0]['companionInfo'].length, itemBuilder: (context, index) { return Container( color: Colors.red, height: 40, width: 40, child: const Text("Test"), ); }, ), ), ], ), ), ), )
补充说明
如果你的ListView需要水平滚动,可以设置scrollDirection: Axis.horizontal,但此时要确保垂直方向有固定高度,否则会触发类似的垂直无界约束错误。
内容的提问来源于stack exchange,提问作者Saad Bashir
相关产品推荐
相关产品推荐

