Flutter中Divider/VerticalDivider不显示仅占空间原因及解决方法
问题诱因
- 组件适配逻辑和父容器约束不匹配:
Divider是水平方向分隔线,默认逻辑是填充父组件的水平可用宽度,直接放入Row内部时,Row的水平主轴为无界约束,Divider无法获取明确宽度边界,最终渲染宽度为0,因此只会占据设置的高度空间,看不到实际的分隔线绘制。 - 后续测试使用的
VerticalDivider是垂直方向分隔线,默认逻辑是填充父组件的垂直可用高度,直接放入Row时如果没有给Row设置明确的垂直高度约束,VerticalDivider无法获取明确高度边界,最终渲染高度为0,同样无法正常显示。 - 两类分隔线都属于依赖父容器跨轴约束确定自身绘制尺寸的组件,没有对应约束时,仅会按设置的主轴尺寸占位,跨轴绘制尺寸为0,自然无法看到视觉效果。
解决方案
根据需要的分隔线方向选择对应写法即可:
- 如果要在
Row中放置垂直竖线分隔符,给Row外层包裹明确高度的容器,让VerticalDivider能拿到有效高度约束:
SizedBox( height: 25, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: const [ VerticalDivider(color: Colors.black, thickness: 1, indent: 50, width: 25,), SizedBox(width: 10), VerticalDivider(color: Colors.black, thickness: 1, indent: 50, width: 25,), SizedBox(width: 10), VerticalDivider(color: Colors.black, thickness: 1, indent: 50, width: 25,), SizedBox(width: 10), VerticalDivider(color: Colors.black, thickness: 1, indent: 50, width: 25,), ], ), )
- 如果要在
Row中放置水平横线分隔符,给每个Divider外层包裹明确宽度的容器,让Divider能拿到有效宽度约束:
Row( mainAxisAlignment: MainAxisAlignment.center, children: const [ SizedBox( width: 50, child: Divider(color: Colors.black, thickness: 1, height: 25,), ), SizedBox(width: 10), SizedBox( width: 50, child: Divider(color: Colors.black, thickness: 1, height: 25,), ), SizedBox(width: 10), SizedBox( width: 50, child: Divider(color: Colors.black, thickness: 1, height: 25,), ), SizedBox(width: 10), SizedBox( width: 50, child: Divider(color: Colors.black, thickness: 1, height: 25,), ), ], )
内容的提问来源于stack exchange,提问作者Emir Bolat
相关产品推荐
相关产品推荐

