How to bind data to the Flutter Sparkline chart (SfSparkLineChart) ?
Description
This article explains how to bind the data source to the flutter sparkline chart.
Solution
There are two different ways to bind the data source to the SfSparklineChart widget. One is directly binding the data, for example list of y values to the data property of SfSparkLineChart widget, and another one is binding the custom data source using SfSparkLineChart.custom.
Using the data property
Follow these steps to bind the data source to the spark line chart using the data property.
Step 1: Initialize the data source sparkChartData of required type and here, declared the type as double.
List<double> sparkChartData = <double>[ 10, 6, 8, -5, 11, 5, -2, 7, -3, 6, 8, 10 ];
Step 2: In the widget build method, initialize the SfSparkLineChart and assign the sparkChartData to the data property.
Widget build(BuildContext context) { // Assigning our sparkChartData to the data property. SfSparkLineChart(data: sparkChartData) }
Thus, the sparkline chart is rendered with the given data source.
Screenshot
Binding Custom data source
Here, you can define our custom type data source. By using the dataCount property, you can assign the number of data and then you can map x and y value of our data source using the xValueMapper and yValueMapper, respectively.
Following instructions explains how to bind the custom data source to the SfSparkLineChart widget.
Step 1: Initialize the data source sparkChartData of custom type. Here, initialized the data of _SalesData.
List<_SalesData> sparkChartData = [ _SalesData('Jan', 35), _SalesData('Feb', 28), _SalesData('Mar', 34), _SalesData('Apr', 32), _SalesData('May', 40) ];
Step 2: In the widget build method, initialize the SfSparkLineChart and bind the xValueMapper and yValueMapper, then assign the number of data count to dataCount property.
SfSparkLineChart.custom( // Binding the x values xValueMapper: (int index) => sparkChartData[index].year, // Binding the y values yValueMapper: (int index) => sparkChartData[index].sales, // Assigning the number of data. dataCount: 5, ),
To know more on axis types, find the user guide. Thus, the sparkline chart is rendered with the custom data source.
Screenshot