如何使用Flutter实现下图所示的UI界面?
实现中间粗两端渐变消失的分隔线
你要实现的是中间粗、向两端平滑渐变消失的分隔线,用普通Container+Stack很难做出这种渐变过渡效果,下面提供两种可行的实现方案:
方案一:使用CustomPaint自定义绘制(推荐)
这种方式灵活性最高,能精确控制线条的粗细变化和渐变范围:
class GradientDivider extends StatelessWidget { final double height; final Color color; final double width; const GradientDivider({ Key? key, this.height = 4, this.color = Colors.grey, this.width = double.infinity, }) : super(key: key); @override Widget build(BuildContext context) { return SizedBox( width: width, height: height, child: CustomPaint( painter: _GradientDividerPainter(color: color), ), ); } } class _GradientDividerPainter extends CustomPainter { final Color color; _GradientDividerPainter({required this.color}); @override void paint(Canvas canvas, Size size) { final paint = Paint() ..shader = LinearGradient( colors: [Colors.transparent, color, color, Colors.transparent], stops: const [0.0, 0.2, 0.8, 1.0], begin: Alignment.centerLeft, end: Alignment.centerRight, ).createShader(Rect.fromLTWH(0, 0, size.width, size.height)); canvas.drawRRect( RRect.fromRectAndRadius( Rect.fromLTWH(0, 0, size.width, size.height), Radius.circular(size.height / 2), ), paint, ); } @override bool shouldRepaint(covariant CustomPainter oldDelegate) => false; }
使用示例:
GradientDivider(color: Colors.blue, height: 3)
方案二:用Stack+LinearGradient快速实现
如果不想自定义绘制,可通过Stack嵌套渐变容器模拟效果(需背景为纯色):
Widget gradientDivider(BuildContext context) { final screenWidth = MediaQuery.of(context).size.width; return SizedBox( height: 4, width: double.infinity, child: Stack( children: [ // 中间实心线条 Center( child: Container( width: screenWidth * 0.6, height: 4, decoration: BoxDecoration( color: Colors.grey, borderRadius: BorderRadius.circular(2), ), ), ), // 左侧渐变遮罩(颜色需与背景一致) Align( alignment: Alignment.centerLeft, child: Container( width: screenWidth * 0.2, height: 4, decoration: BoxDecoration( gradient: LinearGradient( colors: [Colors.white, Colors.grey], begin: Alignment.centerLeft, end: Alignment.centerRight, ), ), ), ), // 右侧渐变遮罩(颜色需与背景一致) Align( alignment: Alignment.centerRight, child: Container( width: screenWidth * 0.2, height: 4, decoration: BoxDecoration( gradient: LinearGradient( colors: [Colors.white, Colors.grey], begin: Alignment.centerRight, end: Alignment.centerLeft, ), ), ), ), ], ), ); }
内容的提问来源于stack exchange,提问作者Rohit Chaurasiya
相关产品推荐
相关产品推荐

