Flutter中ListView内嵌Stack出现RenderStack无限布局错误的解决方法
解决ListView中RenderStack无限大小的错误
这个问题的核心原因很明确:ListView的列表项没有提供固定的高度约束,而Stack作为你的列表项根组件,它的父级给它的约束是高度可以无限大(0.0<=h<=Infinity),Stack本身无法在无限空间中确定自己的尺寸,所以就抛出了Render Box错误。
要解决这个问题,你只需要给Stack包裹一个明确高度的容器,让Stack知道自己的可用空间是有限的。根据你布局里的元素尺寸,我们可以计算出Stack需要的总高度:
- 圆形Container的底部位置是
20 + 100 = 120 - 黑色Container的底部位置是
80 + (屏幕高度*0.12)
我们取这两个值中的较大者作为Stack的总高度,这样就能完全容纳两个层叠的组件。
修改后的代码如下:
import 'dart:math' as math; // 需要导入math包来计算最大值 // ... 你的其他代码 ... Widget _buildCard(BuildContext context, int index) { final screenHeight = MediaQuery.of(context).size.height; final blackContainerHeight = screenHeight * 0.12; // 计算Stack需要的总高度,确保能容纳两个组件 final totalStackHeight = math.max(20 + 100, 80 + blackContainerHeight); return SizedBox( height: totalStackHeight, child: Stack( alignment: Alignment.center, children: <Widget>[ Positioned( top: 80.0, right: 30.0, left: 30.0, child: Container( height: blackContainerHeight, decoration: const BoxDecoration(color: Colors.black), ), ), const Positioned( top: 20, child: Container( height: 100, width: 100, decoration: BoxDecoration( color: Colors.white, shape: BoxShape.circle, border: Border.all(color: Colors.black, width: 13.0), ), ), ) ], ), ); }
额外说明:
如果你不想手动计算高度,也可以使用IntrinsicHeight组件包裹Stack,它会自动计算子组件需要的最大高度,但要注意IntrinsicHeight会带来一定的性能开销,在列表项较多的情况下不推荐使用。
内容的提问来源于stack exchange,提问作者Noam
相关产品推荐
相关产品推荐

