用fl_chart0300绘制的折线图我想点击折线后数据就显示出来
您可以使用LineTouchData类来实现点击折线后显示数据的功能。以下是一个简单的示例代码:
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
class LineChartSample extends StatefulWidget {
  @override
  _LineChartSampleState createState() => _LineChartSampleState();
}
class _LineChartSampleState extends State<LineChartSample> {
  List<FlSpot> _data = [
    FlSpot(0, 2),
    FlSpot(1, 3),
    FlSpot(2, 4),
    FlSpot(3, 5),
    FlSpot(4, 6),
    FlSpot(5, 7),
    FlSpot(6, 8),
    FlSpot(7, 9),
    FlSpot(8, 10),
  ];
  int _touchedIndex;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Line Chart Sample'),
      ),
      body: LineChart(
        LineChartData(
          lineTouchData: LineTouchData(
            touchCallback: (LineTouchResponse touchResponse) {
              if (touchResponse.lineBarSpots.length > 0 &&
                  touchResponse.lineBarSpots.first != null) {
                final touchedSpot = touchResponse.lineBarSpots.first;
                setState(() {
                  _touchedIndex = touchedSpot.spotIndex;
                });
              } else {
                setState(() {
                  _touchedIndex = null;
                });
              }
            },
            handleBuiltInTouches: true,
          ),
          lineBarsData: [
            LineChartBarData(
              spots: _data,
              isCurved: true,
              colors: [Colors.blue],
              barWidth: 3,
              dotData: FlDotData(show: false),
            ),
          ],
          minY: 0,
          titlesData: FlTitlesData(
            bottomTitles: SideTitles(
              showTitles: true,
              getTitles: (value) {
                return value.toInt().toString();
              },
            ),
            leftTitles: SideTitles(
              showTitles: true,
            ),
          ),
        ),
      ),
      bottomNavigationBar: _touchedIndex != null
          ? Container(
              height: 50,
              color: Colors.blue,
              child: Center(
                child: Text(
                  'Value: ${_data[_touchedIndex].y}',
                  style: TextStyle(fontSize: 18, color: Colors.white),
                ),
              ),
            )
          : null,
    );
  }
}
在上面的代码中,我们使用LineTouchData类来处理折线的触摸事件,并在touchCallback回调中判断是否有触摸点,如果有,则显示相应的数据。我们还使用_touchedIndex变量来跟踪当前被触摸的点的索引,并在底部导航栏中显示相关数据。
原文地址: https://www.cveoy.top/t/topic/Zeh 著作权归作者所有。请勿转载和采集!