Skip to content

Instantly share code, notes, and snippets.

@imaNNeo
Created March 18, 2021 23:04
Show Gist options
  • Save imaNNeo/7eaf2ac51c9b870e5c61abd47275a328 to your computer and use it in GitHub Desktop.
Save imaNNeo/7eaf2ac51c9b870e5c61abd47275a328 to your computer and use it in GitHub Desktop.
BarChart -> show persist tooltip, and change color when click happens on bars.
import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'FlChart Demo',
showPerformanceOverlay: false,
theme: ThemeData(
primaryColor: const Color(0xff262545),
primaryColorDark: const Color(0xff201f39),
brightness: Brightness.dark,
),
home: Scaffold(
backgroundColor: Color(0xffdddddd),
appBar: AppBar(
title: Text("fl_chart"),
),
body: MyBarChart(),
),
);
}
}
class MyBarChart extends StatefulWidget {
@override
_MyBarChartState createState() => _MyBarChartState();
}
class _MyBarChartState extends State<MyBarChart> {
Color touchedColor;
Color defaultColor;
int selectedBarIndex;
List<double> values = [4, 2, 5, 8, 2];
List<int> touchedIndices = [];
int lastTouchStartOnIndex = -1;
@override
void initState() {
super.initState();
touchedColor = Colors.blueAccent;
defaultColor = touchedColor.withOpacity(0.4);
}
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: EdgeInsets.only(right: 40),
child: AspectRatio(
aspectRatio: 2,
child: BarChart(
BarChartData(
alignment: BarChartAlignment.spaceEvenly,
barGroups: values.asMap().entries.map((MapEntry<int, double> entry) {
final xValue = entry.key;
final yValue = entry.value;
final touched = touchedIndices.contains(xValue);
return BarChartGroupData(
x: xValue,
barRods: [
BarChartRodData(
y: yValue,
colors: [
touched ? touchedColor : defaultColor,
],
)
],
showingTooltipIndicators: touched ? [0] : []);
}).toList(),
maxY: 10,
barTouchData: BarTouchData(
handleBuiltInTouches: false,
touchCallback: (barTouchResponse) {
if (barTouchResponse.touchInput is PointerDownEvent &&
barTouchResponse.spot != null) {
lastTouchStartOnIndex = barTouchResponse.spot.touchedBarGroupIndex;
} else if (barTouchResponse.touchInput is PointerUpEvent) {
final PointerUpEvent PointerUpEven = barTouchResponse.touchInput;
// Tap happened
setState(() {
if (touchedIndices.contains(lastTouchStartOnIndex)) {
touchedIndices.remove(lastTouchStartOnIndex);
} else {
touchedIndices.add(lastTouchStartOnIndex);
}
lastTouchStartOnIndex = -1;
});
}
},
),
),
),
),
),
);
}
}
@imaNNeo
Copy link
Author

imaNNeo commented Mar 18, 2021

bar_click

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment