我希望折线图中包含的值的最大值和最小值有标签。我使用 fl_chart 插件来构建这个折线图。
我在这里使用折线图 这是我的代码。
LineChart(LineChartData(
lineTouchData: LineTouchData(
touchTooltipData: LineTouchTooltipData(
fitInsideHorizontally: true,
tooltipBgColor: Colors.white,
getTooltipItems: (List<LineBarSpot> touchedBarSpots) {
return touchedBarSpots.map((barSpot) {
DateTime date =
DateTime.fromMillisecondsSinceEpoch(barSpot.x.toInt());
String formattedDate =
DateFormat('dd MMMM yyyy', 'id_Id').format(date);
return LineTooltipItem(
'${barSpot.y} \n $formattedDate',
const TextStyle(
fontFamily: 'Jost*',
fontSize: 12,
fontWeight: FontWeight.bold,
color: Colors.orangeAccent,
),
);
}).toList();
}),
getTouchedSpotIndicator:
(LineChartBarData barData, List<int> spotIndexes) {
return spotIndexes.map((spotIndex) {
return TouchedSpotIndicatorData(
const FlLine(
color: Color.fromARGB(255, 77, 77, 77),
strokeWidth: 1,
dashArray: [4, 4],
),
FlDotData(
getDotPainter: (spot, percent, barData, index) {
return FlDotCirclePainter(
radius: 5.5,
color: gradientColors[0],
strokeWidth: 2,
strokeColor: Colors.white,
);
},
),
);
}).toList();
}),
如果我理解正确的话,您想要示例 5 之类的内容:https://app.flchart.dev/#/line
您可以将
showingTooltipIndicators
添加到您的 LineChartData
https://pub.dev/documentation/fl_chart/latest/fl_chart/LineChartData/showingTooltipIndicators.html
示例:
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
class FlChartExampleChart extends StatefulWidget {
const FlChartExampleChart({super.key});
@override
State<FlChartExampleChart> createState() => _FlChartExampleChartState();
}
class _FlChartExampleChartState extends State<FlChartExampleChart> {
final spots = const [
FlSpot(1.0, 10.1),
FlSpot(4.0, 12.2),
FlSpot(9.0, 8.8),
FlSpot(12.0, 6.9),
FlSpot(13.0, 7.3),
];
late List<int> indexesToShow;
@override
void initState() {
super.initState();
// TODO: find the min and max index dynamically
// indexes are the index of the FlSpot in the [spots] list
indexesToShow = [1, 3];
}
@override
Widget build(BuildContext context) {
final lineBarsData = [
LineChartBarData(
showingIndicators: indexesToShow,
spots: spots,
)
];
return Scaffold(
appBar: AppBar(
title: const Text('FL Chart'),
),
body: SafeArea(
child: LineChart(
LineChartData(
showingTooltipIndicators: indexesToShow
.map(
(index) => ShowingTooltipIndicators(
[
LineBarSpot(
lineBarsData[0],
0,
spots[index],
),
],
),
)
.toList(),
lineBarsData: lineBarsData,
lineTouchData: const LineTouchData(
// enabled must be true and handleBuiltInTouches must be false
// to make the showingIndicators work
enabled: true,
handleBuiltInTouches: false,
),
minY: 0,
maxY: 20,
),
),
),
);
}
}