Flutter中实现容纳ListView的Container自适应高度方法
解决Flutter中Container自适应ListView高度的问题
嘿,这问题我之前也碰到过!你现在的核心问题是给Container设了固定的height:400,导致ListView内容超过这个高度时就被截断了。要实现Container随ListView内容自动增高,只需要做两个关键修改:
- 移除Container的固定高度设置
- 给ListView添加
shrinkWrap: true属性
修改后的完整代码:
Container( // 移除固定height,让Container自适应子组件高度 child: ListView.builder( padding: EdgeInsets.only(top: 5), physics: NeverScrollableScrollPhysics(), // 保持这个设置,禁止ListView自身滚动 shrinkWrap: true, // 关键:让ListView只占用实际需要的高度 itemCount: weatherList.length, itemBuilder: (context, i) { return SizedBox( height: 60, child: Card( color: Colors.transparent, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Padding( padding: const EdgeInsets.only(left: 10.0), child: Text(weatherList[i].weekName), ), Column( children: <Widget>[ weatherList[i].weekIcon, Text(weatherList[i].weekTemper), ], ), Padding( padding: const EdgeInsets.only(right: 10.0), child: Text(weatherList[i].weekdust), ), ], ), ), ); }, ), );
原理说明:
shrinkWrap: true会让ListView不再试图占满父组件的全部可用空间,而是计算所有item的高度总和,把自己的高度设置为这个总和。- 去掉Container的固定height后,它会自动适应子组件(也就是ListView)的实际高度,这样不管
weatherList里有多少条数据,Container都会跟着自动增高,所有内容都能完整显示出来。
内容的提问来源于stack exchange,提问作者evergreen
相关产品推荐
相关产品推荐

