ListView嵌套于Row和Column中无法显示内容的原因咨询
问题原因与解决方案
你遇到的问题核心是垂直方向布局约束缺失:
虽然Flexible已经为ListView分配了水平方向的可用空间,但外层Column默认不会给子组件(这里是Row)分配垂直方向的可用空间,而ListView作为滚动组件,默认需要明确的垂直尺寸约束才能渲染内容。
以下是几种可行的解决方式:
方法1:用Expanded包裹Row
让Row在Column中占据垂直方向的可用空间,间接给ListView提供垂直约束:
body: Center( child: Column( children: <Widget>[ Expanded( child: Row( children: <Widget>[ Flexible( child: ListView( children: [ Text('Text 1'), Text('Text 2'), ], ), ), ], ), ), ], ), ),
方法2:给ListView设置shrinkWrap: true
让ListView根据自身内容高度自适应,不需要父组件提供固定垂直尺寸:
body: Center( child: Column( children: <Widget>[ Row( children: <Widget>[ Flexible( child: ListView( shrinkWrap: true, children: [ Text('Text 1'), Text('Text 2'), ], ), ), ], ), ], ), ),
注意:如果列表内容过多,这种方式可能会导致内容超出屏幕,建议配合physics: NeverScrollableScrollPhysics()或外层约束一起使用。
方法3:给ListView包裹带固定高度的Container
直接为ListView指定垂直方向的固定高度:
body: Center( child: Column( children: <Widget>[ Row( children: <Widget>[ Flexible( child: Container( height: 200, child: ListView( children: [ Text('Text 1'), Text('Text 2'), ], ), ), ), ], ), ], ), ),
内容的提问来源于stack exchange,提问作者bzalar
相关产品推荐
相关产品推荐

