您可以使用 GestureDetector 在折线图上监听单击事件,并获取点击位置的坐标。然后,您可以根据坐标找到最接近的折线点,并显示该点的数据。最后,您可以使用 Positioned 将数据放置在折线点上方。

以下是一个示例代码:

import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';

class LineChartWithClick extends StatefulWidget {
  @override
  _LineChartWithClickState createState() => _LineChartWithClickState();
}

class _LineChartWithClickState extends State<LineChartWithClick> {
  List<FlSpot> _spots = [
    FlSpot(0, 4),
    FlSpot(1, 3.5),
    FlSpot(2, 4.5),
    FlSpot(3, 1),
    FlSpot(4, 3),
    FlSpot(5, 4),
    FlSpot(6, 6),
    FlSpot(7, 5),
    FlSpot(8, 7),
    FlSpot(9, 6),
    FlSpot(10, 8),
    FlSpot(11, 9),
    FlSpot(12, 11),
  ];

  int _touchedIndex = -1;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTapUp: (TapUpDetails details) {
        setState(() {
          _touchedIndex = -1;
          // Find the nearest spot to the tap position
          for (int i = 0; i < _spots.length; i++) {
            final touchX = details.localPosition.dx;
            final touchY = details.localPosition.dy;
            final spotX = _spots[i].x;
            final spotY = _spots[i].y;

            final distance = (touchX - spotX) * (touchX - spotX) + (touchY - spotY) * (touchY - spotY);

            if (distance < 100) {
              // If the distance is less than 100, consider it as a touch event
              _touchedIndex = i;
              break;
            }
          }
        });
      },
      child: Stack(
        children: [
          LineChart(
            LineChartData(
              lineBarsData: [
                LineChartBarData(
                  spots: _spots,
                ),
              ],
            ),
          ),
          if (_touchedIndex != -1)
            Positioned(
              left: _spots[_touchedIndex].x - 30,
              top: _spots[_touchedIndex].y - 40,
              child: Container(
                width: 60,
                height: 30,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(10),
                  color: Colors.grey[800],
                ),
                child: Center(
                  child: Text(
                    '${_spots[_touchedIndex].y}',
                    style: TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }
}

在这个示例中,我们使用了一个 Stack 来放置折线图和数据。我们使用 GestureDetector 来监听点击事件,并在点击位置找到最接近的折线点。如果找到了一个折线点,我们就将 _touchedIndex 设置为该点的索引,并使用 Positioned 将数据放置在该点上方。在这个示例中,我们使用了一个宽度为 60、高度为 30 的 Container 来显示数据。

请注意,为了简单起见,我们在这个示例中只显示了 y 轴的值。如果您需要显示 x 轴的值,您需要将 x 轴的值也添加到 _spots 列表中,并在数据显示时使用 _spots[_touchedIndex].x 来获取 x 轴的值。

Fl_chart (0.30.0) 折线图点击显示数据点

原文地址: https://www.cveoy.top/t/topic/mjzW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录