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 a data source to the SfSparklineChart widget:
Directly binding the data (e.g., list of y values) to the data property
Binding a 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. In this example, we're using 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 a custom type data source. By using the dataCount property, you can specify the number of data points, and then map x and y values of your data source using the xValueMapper and yValueMapper respectively.
Follow these steps to bind a custom data source to the SfSparklineChart widget:
Step 1: Initialize the data source sparkChartData of custom type. In this example, we're using _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 learn more on axis types, find the user guide. Thus, the sparkline chart is rendered with the custom data source.
Screenshot