Flutter 中如何为 Container 组件实现双色边框效果?
Flutter实现Renderflex警告同款双色边框
完全可以实现,Flutter官方的Renderflex溢出警告的双色斜条纹边框,无法直接通过BoxDecoration的Border属性配置实现,下面是两种常用的实现方案:
方案1:自定义CustomPainter绘制(效果最贴合官方警告)
这种方式可以1:1还原官方的双色条纹边框效果,灵活度最高:
import 'package:flutter/material.dart'; class WarningBorderPainter extends CustomPainter { final double strokeWidth; final Color color1; final Color color2; final double stripeWidth; WarningBorderPainter({ this.strokeWidth = 4, this.color1 = Colors.yellow, this.color2 = Colors.black, this.stripeWidth = 10, }); @override void paint(Canvas canvas, Size size) { final rect = Rect.fromLTWH(0, 0, size.width, size.height); final path = Path() ..addRRect(RRect.fromRectAndRadius(rect, Radius.circular(0))) ..lineTo(0, size.height) ..close(); final paint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = strokeWidth; // 绘制斜向条纹 double position = -size.height; while (position < size.width + size.height) { path.reset(); path.moveTo(position, 0); path.lineTo(position + stripeWidth, 0); path.lineTo(position + stripeWidth + size.height, size.height); path.lineTo(position + size.height, size.height); path.close(); path = path.shift(Offset(0, 0))..intersect(Path()..addRect(rect.inflate(strokeWidth/2))); paint.color = (position ~/ stripeWidth) % 2 == 0 ? color1 : color2; canvas.drawPath(path, paint); position += stripeWidth; } } @override bool shouldRepaint(covariant WarningBorderPainter oldDelegate) { return strokeWidth != oldDelegate.strokeWidth || color1 != oldDelegate.color1 || color2 != oldDelegate.color2 || stripeWidth != oldDelegate.stripeWidth; } }
使用的时候直接套在你的组件外层即可:
CustomPaint( painter: WarningBorderPainter(), child: Container( padding: EdgeInsets.all(8), child: Text('My border'), ), )
方案2:嵌套容器+渐变快速实现(适合静态简单场景)
如果不需要完全和官方效果一致,也可以用嵌套容器+渐变快速实现双色边框效果:
Container( padding: EdgeInsets.all(4), // 这个值等于边框宽度 decoration: BoxDecoration( gradient: LinearGradient( colors: [Colors.yellow, Colors.black], begin: Alignment.topLeft, end: Alignment.bottomRight, stops: [0.5, 0.5], ), ), child: Container( color: Colors.white, // 内部背景色和页面背景一致即可 padding: EdgeInsets.all(8), child: Text('My border'), ), )
实现后的双色边框效果如下图:
内容的提问来源于stack exchange,提问作者Defarine
相关产品推荐
相关产品推荐

