Created
March 4, 2022 14:49
-
-
Save imaNNeo/bce3f0169ff3fd6c3f137cdeb5005c0e to your computer and use it in GitHub Desktop.
Toggle showing tooltip on BarChart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:fl_chart/fl_chart.dart'; | |
import 'package:flutter/material.dart'; | |
void main() => runApp(const MyApp()); | |
class MyApp extends StatelessWidget { | |
const MyApp({Key? key}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return const MaterialApp( | |
home: MyHomePage(), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
const MyHomePage({Key? key}) : super(key: key); | |
@override | |
_MyHomePageState createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
late int showingTooltip; | |
@override | |
void initState() { | |
showingTooltip = -1; | |
super.initState(); | |
} | |
BarChartGroupData generateGroupData(int x, int y) { | |
return BarChartGroupData( | |
x: x, | |
showingTooltipIndicators: showingTooltip == x ? [0] : [], | |
barRods: [ | |
BarChartRodData(y: y.toDouble()), | |
], | |
); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
body: Center( | |
child: Padding( | |
padding: const EdgeInsets.all(24), | |
child: AspectRatio( | |
aspectRatio: 2, | |
child: BarChart( | |
BarChartData( | |
barGroups: [ | |
generateGroupData(1, 10), | |
generateGroupData(2, 18), | |
generateGroupData(3, 4), | |
generateGroupData(4, 11), | |
], | |
barTouchData: BarTouchData( | |
enabled: true, | |
handleBuiltInTouches: false, | |
touchCallback: (event, response) { | |
if (response != null && response.spot != null && event is FlTapUpEvent) { | |
setState(() { | |
final x = response.spot!.touchedBarGroup.x; | |
final isShowing = showingTooltip == x; | |
if (isShowing) { | |
showingTooltip = -1; | |
} else { | |
showingTooltip = x; | |
} | |
}); | |
} | |
}, | |
mouseCursorResolver: (event, response) { | |
return response == null || response.spot == null | |
? MouseCursor.defer | |
: SystemMouseCursors.click; | |
} | |
), | |
), | |
), | |
), | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
toggle.mov