How to customize the tooltip using callback events (SfCartesianChart) ?
In this article, we describe how to customize tooltips in Flutter Cartesian Charts by using callback events.
The Flutter Cartesian chart widget provides support for customizing the tooltip in the chart using callback events on rendering. Callback events are functions or methods that you pass as arguments into another function or method, allowing you to perform actions when required. The chart widget provides a callback event called onTooltipRender to customize tooltip contents as needed.
Follow these instructions to customize tooltip contents using callback events:
Customization of tooltip
Step 1: Initialize the SfCartesianChart with TooltipBehavior enabled as true and with all other required properties.
late TooltipBehavior _tooltipBehavior; @overrride void initState(){ _tooltipBehavior = TooltipBehavior(enable: true), super.initState(); } @override Widget build(BuildContext context) { return SfCartesianChart( primaryXAxis: CategoryAxis(), // Enable tooltip tooltipBehavior: _tooltipBehavior, series: <LineSeries<SalesData, String>>[ LineSeries<SalesData, String>( enableTooltip: true, dataSource: ChartData, xValueMapper: (SalesData sales, _) => sales.year, yValueMapper: (SalesData sales, _) => sales.sales, //Enable datalabel settings dataLabelSettings: DataLabelSettings(isVisible: true) ) ] ); }
Step 2: Define the onTooltipRender event in the SfCartesianChart and you can customize the tooltip contents with the arguments such as header, text, pointIndex, seriesIndex, dataPoints, locationX, and locationY.
SfCartesianChart( onTooltipRender: (TooltipArgs args) { if (args.pointIndex == 0) { //Tooltip without header args.header = ''; } if (args.pointIndex == 1) { //Tooltip with customized header args.header = 'Sold'; } if (args.pointIndex == 2) { //Tooltip with X and Y positions of data points args.header = 'x : y'; args.text = '${args.locationX!.floor()} : ${args.locationY!.floor()}'; } if(args.pointIndex == 3) { //Tooltip with formatted DateTime values List<dynamic>? chartdata = args.dataPoints; args.header = DateFormat('d MMM yyyy').format(chartdata[3]!.x); args.text = '${chartdata[3].y}'; } } )
Screenshots
Tooltip without header
Tooltip with customized header
Tooltip with X and Y positions of data points
Tooltip with formatted DateTime values
For more information on tooltip public methods, refer to the user guide.
View the Github Sample here.