【Flutter 专题】114 图解自定义 ACEProgressPainter 对比进度图
import 'package:flutter/material.dart';
class ACEProgressPainter extends CustomPainter {
final Color progressColor;
final double progress;
final double total;
ACEProgressPainter(this.progressColor, this.progress, this.total);
@override
void paint(Canvas canvas, Size size) {
final double progressRatio = progress / total;
final double progressWidth = size.width * progressRatio;
final Paint paint = Paint()
..color = progressColor
..style = PaintingStyle.fill;
canvas.drawRect(Rect.fromLTWH(0, 0, progressWidth, size.height), paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}
class ProgressBarExample extends StatefulWidget {
@override
_ProgressBarExampleState createState() => _ProgressBarExampleState();
}
class _ProgressBarExampleState extends State<ProgressBarExample> {
double progress = 30;
void incrementProgress() {
setState(() {
progress = (progress + 10).clamp(0.0, 100.0);
});
}
@override
Widget build(BuildContext context) {
return Column(
children: [
SizedBox(
height: 5,
width: 100,
child: CustomPaint(
painter: ACEProgressPainter(Colors.blue, progress, 100),
),
),
Text('Progress: $progress%'),
RaisedButton(
child: Text('Increment'),
onPressed: incrementProgress,
),
],
);
}
}
这个代码示例展示了如何使用自定义的ACEProgressPainter
来绘制一个进度条。ProgressBarExample
状态中维护了一个进度值,当按钮被按下时,进度值增加,并且通过setState
触发重新构建,显示新的进度。这里使用了CustomPaint
来渲染进度条,并且通过Colors.blue
设置了进度条的颜色。
评论已关闭