Flutter ListView设置horizontal滚动方向后组件无法显示问题求助
问题根因
该现象是Flutter滚动组件的布局约束特性导致的:
- 垂直方向的ListView会自动给子组件施加水平方向撑满父容器的约束,所以不给子组件设宽度也能正常显示
- 水平方向的ListView只会给子组件施加垂直方向撑满父容器高度的约束,子组件的宽度没有默认约束,如果你的
About组件本身没有固定宽度,就会因为宽度为0导致看不到内容;另外你原来用来做间距的SizedBox只设置了height属性,水平滚动时间距需要用width才会生效。
修复方案
修改ListView下的子组件,给每个子容器加明确宽度、修改间距组件的属性即可,参考修改后的代码:
Widget build(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisSize: MainAxisSize.max, children: [ Container( width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height * 0.385, child: ListView( scrollDirection: Axis.horizontal, // 改成水平滚动 children: [ Container( width: MediaQuery.of(context).size.width * 0.8, // 给子容器加明确宽度,可按需调整 padding: EdgeInsets.all(5), decoration: BoxDecoration( border: Border.all(color: Colors.red), borderRadius: BorderRadius.circular(15), ), child: About(), ), SizedBox( width: 5, // 水平滚动时间距用width属性 ), Container( width: MediaQuery.of(context).size.width * 0.8, // 同样加宽度 padding: EdgeInsets.all(5), decoration: BoxDecoration( border: Border.all(color: Colors.red), borderRadius: BorderRadius.circular(15), ), child: About(), ), ], ), ), // 其余原有代码保持不变
额外优化建议
如果你的子组件数量比较多,推荐把普通ListView替换成ListView.builder做懒加载,减少不必要的渲染开销。
内容的提问来源于stack exchange,提问作者Чак Джонс
相关产品推荐
相关产品推荐

