How to select the data points dynamically in Cartesian charts (SfCartesianChart) ?
This article describes how to select the data points dynamically in Cartesian charts.
The Flutter Cartesian Chart widget provides support to programmatically do the data points selection on the charts using the public methods. Public methods are methods that can be called by using the class object where they are defined. Likewise, our chart widget also has a public method to select the data points in the charts dynamically called as selectionIndex method.
Refer the following instructions, to use the selection public method to select the data points in chart dynamically.
selectionIndex method
The selectionIndex method selects the data points with the specified series and point index.
Step 1: Initialize the SfCartesianChart and SelectionSettings globally with the required properties.
late SfCartesianChart chart; late SelectionBehavior _selectionBehavior; @override void initState(){ _selectionBehavior = SelectionSettings( enable: true, selectedColor: Colors.yellowAccent ); super.initState(); } @override Widget build(BuildContext context) { chart = SfCartesianChart( series: <ColumnSeries<ChartData, num>>[ ColumnSeries<ChartData, num>( dataSource: chartData, xValueMapper: (ChartData data, _) => data.x, yValueMapper: (ChartData data, _) => data.y, selectionSettings: _selectionBehavior) ] ); }
Step 2: Initialize the button and chart in the build method and in the button click event, you can call the public method to select the required data points by passing the series and point index.
@override Widget build(BuildContext context) { return Scaffold( body: Center( child: Column( children: <Widget>[ FlatButton( child: Text('Select'), onPressed: select ), Container(child: chart) ] ) ) ); } void select() { // In the selection method, you can pass the pointIndex and seriesIndex values of the required data point // to be selected. _selectionBehavior.selectionIndex(1, 0); }
Screenshots
Tooltip without header
For more information to use the SelectionBehavior public methods, find the user guide here.