flutter 空心饼图代码
时间: 2023-09-04 10:07:59 浏览: 102
好的,以下是一个简单的空心饼图的 Flutter 代码示例:
```
import 'package:flutter/material.dart';
import 'dart:math';
class DonutChart extends StatelessWidget {
final List<Data> data;
DonutChart({required this.data});
@override
Widget build(BuildContext context) {
return CustomPaint(
size: Size(MediaQuery.of(context).size.width, 250),
painter: DonutChartPainter(data),
);
}
}
class DonutChartPainter extends CustomPainter {
final List<Data> data;
final double _total = 100;
double _start = -90.0;
DonutChartPainter(this.data);
@override
void paint(Canvas canvas, Size size) {
var paint = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 20.0;
final radius = min(size.width / 2, size.height / 2) - (paint.strokeWidth / 2);
double total = data.fold(0, (prev, element) => prev + element.value);
for (var slice in data) {
paint.color = slice.color;
double sweepAngle = (slice.value / total) * 360;
canvas.drawArc(
Rect.fromCircle(center: Offset(size.width / 2, size.height / 2), radius: radius),
radians(_start),
radians(sweepAngle),
false,
paint);
_start += sweepAngle;
}
}
@override
bool shouldRepaint(DonutChartPainter old) {
return old.data != data;
}
double radians(double degree) {
return degree * pi / 180;
}
}
class Data {
final String label;
final double value;
final Color color;
Data({required this.label, required this.value, required this.color});
}
```
需要注意的是,在使用时需要提供一个包含 `Data` 对象的数组,其中每个 `Data` 对象代表一个扇形,包含一个标签、一个值和一个颜色。然后将这个数组传递给 `DonutChart` 组件即可。
另外需要注意的是,这个代码示例只是一个简单的实现,还有很多可以改进的地方,比如添加动画、增加标签等。
阅读全文