Flutter中如何在Card Widget内绘制水平线与垂直线
Flutter Card组件内绘制横竖线条的实现方案
参考效果


以下是三种不同复杂度的实现方案,可根据自身需求选择:
方案1:使用官方内置分割线组件(最简单)
Flutter官方已经提供了现成的分割线组件,无需自定义代码,基础需求优先选这个:
- 水平线使用
Divider组件 - 垂直线使用
VerticalDivider组件
示例代码:
Card( margin: const EdgeInsets.all(16), child: Padding( padding: const EdgeInsets.all(16), child: SizedBox( height: 200, child: Row( children: [ const Expanded(child: Center(child: Text("左侧区域"))), // 垂直线 VerticalDivider( color: Colors.grey.shade400, thickness: 1.5, indent: 20, // 线条顶部留白 endIndent: 20, // 线条底部留白 ), Expanded( child: Column( children: [ const Expanded(child: Center(child: Text("右上区域"))), // 水平线 Divider( color: Colors.grey.shade400, thickness: 1.5, indent: 15, // 线条左侧留白 endIndent: 15, // 线条右侧留白 ), const Expanded(child: Center(child: Text("右下区域"))), ], ) ) ], ), ), ) )
方案2:使用Container装饰器实现(灵活度中等)
如果需要对线条样式做简单自定义,比如实现渐变线条、调整边框位置,用Container的decoration属性即可实现:
// 垂直线实现示例 Container( width: 1.5, height: 160, decoration: BoxDecoration( gradient: LinearGradient( colors: [Colors.transparent, Colors.grey.shade400, Colors.transparent], begin: Alignment.topCenter, end: Alignment.bottomCenter ) ), )
如果需要实现虚线效果,可直接使用flutter_dash第三方包,传入对应方向参数即可快速生成虚线。
方案3:CustomPaint自定义绘制(灵活度最高)
如果需要实现特殊样式的线条,比如两端圆角、间断特效、自定义路径,可通过CustomPaint自己绘制:
class CustomLinePainter extends CustomPainter { final Color lineColor; final double lineWidth; final bool isVertical; CustomLinePainter({ required this.lineColor, required this.lineWidth, required this.isVertical }); @override void paint(Canvas canvas, Size size) { final paint = Paint() ..color = lineColor ..strokeWidth = lineWidth ..strokeCap = StrokeCap.round // 线条两端圆角 ..style = PaintingStyle.stroke; if(isVertical) { canvas.drawLine(Offset(size.width/2, 0), Offset(size.width/2, size.height), paint); } else { canvas.drawLine(Offset(0, size.height/2), Offset(size.width, size.height/2), paint); } } @override bool shouldRepaint(covariant CustomPainter oldDelegate) => false; } // 使用方式 CustomPaint( size: const Size(1.5, 160), painter: CustomLinePainter( lineColor: Colors.grey.shade400, lineWidth: 1.5, isVertical: true ), )
常见问题排查
- 若
VerticalDivider不显示:检查父组件是否明确设置了高度,没有高度约束的话垂直线无法正常渲染 - 若
Divider不显示:检查父组件是否明确设置了宽度,没有宽度约束的话水平线无法正常渲染
内容的提问来源于stack exchange,提问作者Jayswal Viraj
相关产品推荐
相关产品推荐

