Flutter Google Chart Gauge-将标签放置在中心

时间:2019-02-12 12:14:57

标签: charts dart flutter

我正在寻找charts_flutter包裹。我需要实现一个仪表盘图,该仪表盘具有单个段并将其标签值放在仪表盘的中心。请参阅下面的模型文件,其中将来自所需类型的三个图表放置在一行中:

enter image description here

使用Google图表仪表样本,我能够实现所需的仪表,但是,我正在努力根据要求设置标签。 下面是该类,我用于量规,任何帮助/提示如何添加标签将不胜感激:

/// Gauge chart example, where the data does not cover a full revolution in the
/// chart.
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:flutter/material.dart';
import 'dart:math';

class GaugeChart extends StatelessWidget {
  final List<charts.Series> seriesList;
  final bool animate;

  GaugeChart(this.seriesList, {this.animate});

  factory GaugeChart.fromValue(
      {@required double value, @required Color color, bool animate}) {
    return GaugeChart(
      _createDataFromValue(value, color),
      // Disable animations for image tests.
      animate: animate,
    );
  }

  @override
  Widget build(BuildContext context) {
    return charts.PieChart(
      seriesList,
      animate: animate,
      // Configure the width of the pie slices to 30px. The remaining space in
      // the chart will be left as a hole in the center. Adjust the start
      // angle and the arc length of the pie so it resembles a gauge.
      defaultRenderer: charts.ArcRendererConfig(
        arcWidth: 20,
        startAngle: 3 / 5 * pi,
        arcLength: 9 / 5 * pi,
        //arcRendererDecorators: [charts.ArcLabelDecorator(labelPosition: charts.ArcLabelPosition.outside)],
      ),
    );
  }

  static List<charts.Series<GaugeSegment, String>> _createDataFromValue(
      double value, Color color) {
    double toShow = (1 + value) / 2;
    final data = [
      GaugeSegment('Main', toShow, color),
      GaugeSegment('Rest', 1 - toShow, Colors.transparent),
    ];

    return [
      charts.Series<GaugeSegment, String>(
        id: 'Segments',
        domainFn: (GaugeSegment segment, _) => segment.segment,
        measureFn: (GaugeSegment segment, _) => segment.value,
        colorFn: (GaugeSegment segment, _) => segment.color,
        // Set a label accessor to control the text of the arc label.
        labelAccessorFn: (GaugeSegment segment, _) =>
            segment.segment == 'Main' ? '${segment.value}' : null,
        data: data,
      )
    ];
  }
}

/// data type.
class GaugeSegment {
  final String segment;
  final double value;
  final charts.Color color;

  GaugeSegment(this.segment, this.value, Color color)
      : this.color = charts.Color(
            r: color.red, g: color.green, b: color.blue, a: color.alpha);
}

这是使用类的方式:

// value can take values between -1 and 1
GaugeChart.fromValue(value: 0.34, color: Colors.red)

1 个答案:

答案 0 :(得分:2)

我们使用Stack来实现:

return Container(
    width: 120,
    height: 120,
    child: Stack(children: [
        GaugeChart(_getChartData()),
        Center(
            child: Text(
        '$percent',
        ))
    ]));