How to activate chart tooltip initially after the chart widget got rendered (SfCartesianChart) ?
In this article, we described how to activate the chart tooltip initially, after the chart widget got rendered in Flutter application.
The Flutter Cartesian Chart provides support to dynamically active the tooltip of a data point in the chart using the public methods. Public methods are methods that can be called by using the class object where they are defined. In order to dynamically render any data point’s tooltip after the chart is rendered, you can use the addPostFramecallback method of the WidgetBinding mixin whose events gets executed only after the chart widget returned to the build method gets rendered in the Flutter application.
The following steps explains how to dynamically activate the chart tooltip initially, after the chart widget is rendered:
Step 1: First, globally initialize an object for TooltipBehavior class. In order to use the available public methods, define the required properties in its constructor and also initialize a global variable for storing the series animation duration value.
double seriesAnimation = 1500; late TooltipBehavior _tooltipBehavior; @override void initState(){ _tooltipBehavior = TooltipBehavior(enable: true, shouldAlwaysShow: true); super.initState(); }
Step 2: Initialize the SfCartesianChart with all the necessary properties and before returning the chart widget in the build method, call the addPostFrameCallback() method using the instance of the WidgetBinding class. In the callback argument of this method, pass the function, in which call the showByIndex public method of the TooltipBehavior inside a Timer with duration slightly greater than the provided animation duration value so that the tooltip will get automatically rendered initially after the chart animation gets completed.
@override Widget build(BuildContext context) { WidgetsBinding.instance.addPostFrameCallback((_) { // Added 300 milliseconds to the series animation duration and provided it as the duration for the Timer. Timer(Duration(milliseconds: seriesAnimation.toInt() + 300), () { // Activated the tooltip of the second data point’s index. _tooltipBehavior.showByIndex(0, 2); }); }); return Scaffold( appBar: AppBar( title: const Text('Syncfusion Flutter chart'), ), body: SfCartesianChart( primaryXAxis: CategoryAxis(), // Assigned the TooltipBehavior object to the tooltipBehavior property tooltipBehavior: _tooltipBehavior, series: <LineSeries<_ChartData, String>>[ LineSeries<_ChartData, String>( dataSource: chartData, animationDuration: seriesAnimation, xValueMapper: (_ChartData sales, _) => sales.x, yValueMapper: (_ChartData sales, _) => sales.y, ) ], )); }
Thus, once the chart widget gets rendered, the tooltip will get activated automatically in the chart.
Screenshot