How to Modify Chart on Legend Interaction in Flutter Circular Chart?
In Flutter circular chart, the percentage of each segment in a pie chart is calculated based on the total value of all visible segments. When interacting with the legend, the percentage values should update dynamically to reflect the new total. This article explains how to achieve this functionality in Flutter using the SfCircularChart widget.
The following steps explains how to dynamically update percentages based on legend interaction in Flutter Circular Chart.
Step 1: Create a ChartData class to store the category name, value, and computed percentage dynamically. The percentage field will be updated based on the visible segments.
class ChartData {
ChartData(this.x, this.y);
final String x;
final double y;
double percentage = 0;
}
Step 2: In the stateful widget, define the list of data points and a boolean list _isVisible to track the visibility of each segment. The _isVisible list is initialized using List
class CircularChartPercentageState extends State<CircularChartPercentage> {
List<ChartData> chartData = [
ChartData('USA', 20),
ChartData('China', 35),
ChartData('UK', 38),
ChartData('India', 25),
ChartData('Germany', 30),
];
late List<bool> _isVisible;
late Legend _legend;
@override
void initState() {
super.initState();
_legend = const Legend(
isVisible: true,
overflowMode: LegendItemOverflowMode.wrap,
toggleSeriesVisibility: true,
);
_isVisible = List<bool>.filled(chartData.length, true);
}
Step 3: Define the _updatePercentages function, which recalculates the percentages based on the total of only visible segments. It first calculates the sum of all y values from chartData where the corresponding segment is marked as visible in the _isVisible list.
Once the total of visible segments is determined, the function iterates through chartData again and updates each segment’s percentage by dividing its value by the total visible value and multiplying the result by 100.
If a segment is hidden (i.e., its corresponding _isVisible value is false), its percentage is explicitly set to 0. The setState method is then called to update the UI and reflect the newly calculated percentage values dynamically.
void _updatePercentages() {
double total = 0;
for (int i = 0; i < chartData.length; i++) {
if (_isVisible[i]) {
total += chartData[i].y;
}
}
setState(() {
for (int i = 0; i < chartData.length; i++) {
if (_isVisible[i]) {
chartData[i].percentage = (chartData[i].y / total) * 100;
} else {
chartData[i].percentage = 0;
}
}
});
}
Step 4: To manage legend interactions and update data labels, use the following callbacks:
The onLegendTapped callback to toggle the segment’s visibility and update the percentages accordingly. When a legend item is tapped, _isVisible[args.pointIndex!] is toggled between true and false, and _updatePercentages() is called to recalculate the percentages.
The onLegendItemRender callback modifies the legend text to display the updated percentage.
The dataLabelMapper is used to update the segment labels dynamically.
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SfCircularChart(
onLegendItemRender: (args) {
args.text =
'${args.text} (${chartData[args.pointIndex!].percentage.toStringAsFixed(2)}%)';
},
onLegendTapped: (args) {
if (args.pointIndex != null) {
_isVisible[args.pointIndex!] = !_isVisible[args.pointIndex!];
_updatePercentages();
}
},
legend: _legend,
series: <CircularSeries>[
PieSeries<ChartData, String>(
dataSource: chartData,
xValueMapper: (ChartData data, int index) => data.x,
yValueMapper: (ChartData data, int index) => data.y,
dataLabelMapper: (ChartData data, int index) =>
'${data.x}: ${data.percentage.toStringAsFixed(2)}%',
dataLabelSettings: const DataLabelSettings(isVisible: true),
),
],
),
),
);
}
Now, when a legend item is toggled, the chart updates dynamically to reflect the new percentages of visible segments as shown below.
Conclusion
I hope you enjoyed learning about how to modify Chart on legend interaction in Flutter Circular Chart.
You can refer to our Flutter CircularChart feature tour page to leran about its other groundbreaking feature representations. You can also explore our Flutter CircularChart documentation to understand features functionality in depth.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®~~~~, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!