如何为Flutter Scrollbar轨道添加带圆角的边框?
实现带边框和圆角的Flutter滚动条轨道
原生ScrollbarTheme的trackRadius和trackBorderColor属性无法完整实现带圆角边框的轨道效果,因为默认轨道绘制逻辑仅渲染一条竖线。想要实现目标样式,需要通过RawScrollbar结合自定义ScrollbarTrackPainter来完成。
解决方案代码
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { final ScrollController _scrollController = ScrollController(); return MaterialApp( home: Scaffold( body: Stack( children: [ Positioned( left: 0, top: 0, width: 300, height: 500, child: RawScrollbar( controller: _scrollController, thumbVisibility: true, trackVisibility: true, thickness: 8, crossAxisMargin: 6, thumbColor: Colors.blue.shade300, trackColor: Colors.white, // 自定义轨道绘制器 trackPainter: _CustomScrollbarTrackPainter( borderColor: Colors.blue.shade200, borderRadius: BorderRadius.circular(8), trackColor: Colors.white, ), child: SingleChildScrollView( controller: _scrollController, child: Container( width: 300, height: 1500, color: Colors.white, ), ), ), ), ], ), ), ); } } // 自定义滚动条轨道绘制器 class _CustomScrollbarTrackPainter extends ScrollbarTrackPainter { final Color borderColor; final BorderRadius borderRadius; final Color trackColor; _CustomScrollbarTrackPainter({ required this.borderColor, required this.borderRadius, required this.trackColor, }); @override void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) { // 绘制带圆角的边框 final borderPaint = Paint() ..color = borderColor ..style = PaintingStyle.stroke ..strokeWidth = 1; final borderRRect = borderRadius.toRRect(rect); canvas.drawRRect(borderRRect, borderPaint); // 绘制轨道背景(向内收缩1px避免和边框重叠) final trackRect = rect.deflate(1); final trackRRect = borderRadius.toRRect(trackRect); final trackPaint = Paint()..color = trackColor; canvas.drawRRect(trackRRect, trackPaint); } @override bool shouldRepaint(covariant _CustomScrollbarTrackPainter oldDelegate) { return oldDelegate.borderColor != borderColor || oldDelegate.borderRadius != borderRadius || oldDelegate.trackColor != trackColor; } }
关键说明
- 自定义
_CustomScrollbarTrackPainter继承自ScrollbarTrackPainter,重写paint方法先绘制圆角边框,再绘制轨道背景 - 使用
RawScrollbar替代Scrollbar,通过trackPainter参数传入自定义绘制器 - 调整
thickness、crossAxisMargin等参数控制滚动条的尺寸和位置 - 确保
trackVisibility设为true,否则自定义轨道不会显示
内容的提问来源于stack exchange,提问作者F F
相关产品推荐
相关产品推荐

