How to visualizing data from multiple documents in Firestore using Flutter SfCartesianChart?
In this article explains how to render the Flutter Charts using the data stored in multiple documents in the Firestore database.
Please refer this How to render the Flutter chart using the data in Firestore (SfCartesianChart) KB for the Firestore database creation and project configuration.
Step 1: Add Syncfusion® Flutter Charts , Firebase Core and Cloud Firebase packages to your dependencies in pubspec.yaml file. Import the following packages in main.dart file to access the packages.
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:syncfusion_flutter_charts/charts.dart';
Step 2: Here is the data document structure we have in Firestore database with collection name as chartData. There are three different documents in this collection, and each document has a series name in the seriesName field and data points in the value field.
Step 3: To parse the given JSON object, need to create two classes ChartData and SalesData. Using these classes, converted the firestore values to the chart input.
class ChartData { final String seriesName; final List<SalesData> data; ChartData( this.seriesName, this.data, ); factory ChartData.fromJson(Map<String, dynamic> parsedJson) { List<SalesData> dataPoints = []; int length = parsedJson['value'].length; for (int i = 0; i < length; i++) { dataPoints.add(SalesData.fromJson(parsedJson['value']['$i'])); } return ChartData(parsedJson['seriesName'], dataPoints); } } class SalesData { SalesData(this.date, this.yValue); final DateTime date; final double yValue; factory SalesData.fromJson(Map<String, dynamic> parsedJson) { return SalesData(DateFormat("yyyy-MM-dd").parse(parsedJson['date']), parsedJson['yValue']); } }
Step 4: A future function named getDataFromFireStore has been declared with a return type of void. This function utilizes the FirebaseFirestore instance to retrieve a collection of documents from the chartData collection in the Firestore database. Subsequently, it maps through the snapshots of the documents, converting each document's data into an object of the ChartData class by invoking the fromJson method. Finally, it adds all these ChartData objects to the chartData list and returns the snapShotsValue.
Future<void> getDataFromFireStore() async { var snapShotsValue = await FirebaseFirestore.instance.collection('chartData').get(); chartData.addAll( snapShotsValue.docs.map((e) => ChartData.fromJson(e.data())).toList()); return snapShotsValue as dynamic; }
Step 5: Next, we will wrap the SfCartesianChart widget inside the FutureBuilder and assign the getDataFromFireStore function to the future property. Inside the build function, we will return the SfCartesianChart with chartData if the snapshot has data and assign the populated values to dataSource property of the SfCartesianChart widget; otherwise, we will return the CircularProgressIndicator.
FutureBuilder( future: getDataFromFireStore(), builder: (context, snapshot) { if (snapshot.hasData) { return SfCartesianChart( plotAreaBorderWidth: 0, legend: Legend( isVisible: true, position: LegendPosition.bottom), primaryYAxis: NumericAxis( axisLine: const AxisLine(width: 0), rangePadding: ChartRangePadding.round, majorTickLines: const MajorTickLines(width: 0), ), primaryXAxis: DateTimeAxis( edgeLabelPlacement: EdgeLabelPlacement.shift, dateFormat: DateFormat('dd-MMM'), majorGridLines: const MajorGridLines(width: 0), majorTickLines: const MajorTickLines(width: 0), ), series: buildLineSeries(chartData)); } else { return const CircularProgressIndicator(); } }, ) List<LineSeries<SalesData, DateTime>> buildLineSeries( List<ChartData> chartData) { List<LineSeries<SalesData, DateTime>> series = []; List<Color> seriesColor = [ Color(0XFFd4862f), Color(0XFFc3c2c2), Color(0XFF07cc67) ]; for (var i = 0; i < chartData.length; i++) { series.add(LineSeries<SalesData, DateTime>( dataSource: chartData[i].data, color: seriesColor[i], markerSettings: MarkerSettings(isVisible: true, color: seriesColor[i]), name: chartData[i].seriesName, xValueMapper: (SalesData data, _) => data.date, yValueMapper: (SalesData data, _) => data.sales)); } return series; }
As a result, the chart is rendered with nested data from Firestore. An image of the data in Firestore and the chart rendered with the corresponding data is shown below.
Output
Conclusion
I hope you enjoyed learning about how to visualizing data from multiple documents in Firestore using Flutter SfCartesianChart.
You can refer to our Flutter Cartesian Chart’s feature tour page to know about its other groundbreaking feature representations. You can also explore our Flutter Cartesian Chart documentation to understand how to present and manipulate data.
For current customers, you can check out our Flutter components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our Flutter Cartesian Chart and other Flutter components.
If you have any queries or require clarifications, please let us know in the comment section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!