How to select the data points dynamically in SfCartesianChart?
This article describes how to select data points dynamically in Flutter Cartesian charts.
The Flutter Cartesian Chart widget provides support to programmatically select data points on charts using public methods. Public methods are methods that can be called by using the class object where they are defined. Our chart widget includes a public method called selectionIndex to dynamically select data points in charts.
Follow these instructions to use the selection public method to select data points in charts 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 on using the SelectionBehavior public methods, find the user guide here.