如何使用charts_flutter包在Flutter中显示工具提示

2024-03-12

我在用https://pub.dev/packages/charts_flutter https://pub.dev/packages/charts_flutter对于我的应用程序中的图表。我想在按下 PointsLineChart 中的点时显示工具提示。

有什么办法显示工具提示吗?


我为此苦苦挣扎了一个小时,终于找到了解决方案github问题 https://github.com/google/charts/issues/58#issuecomment-488695645我对代码进行了一些修改,以将点击的值显示为工具提示。

import 'dart:math';

import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart';
import 'package:charts_flutter/src/text_element.dart';
import 'package:charts_flutter/src/text_style.dart' as style;

class Chart extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return LineChart(
      _createSampleData(),
      behaviors: [
        LinePointHighlighter(
          symbolRenderer: CustomCircleSymbolRenderer()  // add this line in behaviours
        )
      ],
      selectionModels: [
        SelectionModelConfig(
          changedListener: (SelectionModel model) {
            if(model.hasDatumSelection){
              final value = model.selectedSeries[0].measureFn(model.selectedDatum[0].index);
              CustomCircleSymbolRenderer.value = value;  // paints the tapped value 
             }
          }
        )
      ],
    );
  }

  List<Series<LinearSales, int>> _createSampleData() {
    final data = [
      new LinearSales(0, 5),
      new LinearSales(1, 25),
      new LinearSales(2, 100),
      new LinearSales(3, 75),
    ];
    return [
      new Series<LinearSales, int>(
        id: 'Sales',
        colorFn: (_, __) => MaterialPalette.blue.shadeDefault,
        domainFn: (LinearSales sales, _) => sales.year,
        measureFn: (LinearSales sales, _) => sales.sales,
        data: data,
      )
    ];
  }
}

class CustomCircleSymbolRenderer extends CircleSymbolRenderer {
static String value;
  @override
  void paint(ChartCanvas canvas, Rectangle<num> bounds, {List<int> dashPattern, Color fillColor, Color strokeColor, double strokeWidthPx}) {
    super.paint(canvas, bounds, dashPattern: dashPattern, fillColor: fillColor, strokeColor: strokeColor, strokeWidthPx: strokeWidthPx);
    canvas.drawRect(
      Rectangle(bounds.left - 5, bounds.top - 30, bounds.width + 10, bounds.height + 10),
      fill: Color.white
    );
    var textStyle = style.TextStyle();
    textStyle.color = Color.black;
    textStyle.fontSize = 15;
    canvas.drawText(
      TextElement("$value", style: textStyle),
        (bounds.left).round(),
        (bounds.top - 28).round()
    );
  }
}
class LinearSales {
  final int year;
  final int sales;
  LinearSales(this.year, this.sales);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用charts_flutter包在Flutter中显示工具提示 的相关文章