We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

How to render the Flutter chart using JSON data stored in Firebase database (SfCartesianChart) ?

Platform: Flutter |
Control: SfCartesianChart |
Published Date: August 13, 2020 |
Last Revised Date: May 18, 2021

Using the Firebase REST API and HTTP client, you can retrieve the JSON data from the Firebase database and also with the help of the deserialization concept (parsing of raw JSON data to dart object model) you can convert the retrieved JSON data to chart data list for the Flutter Cartesian chart.

The Firebase Realtime Database is a cloud-hosted database. A Data is stored as JSON and synchronized in real-time to every connected client. You can use any Firebase Realtime Database URL as a REST endpoint and send requests from the HTTP client, in order to access the JSON data.

 

Refer the following instructions, to render chart using the JSON data stored in Firebase Database.

 

Retrieval of JSON data string using the Firebase REST API and HTTP client

 

Step 1: First, copy the Firebase Realtime Database URL from the Firebase console, which can be used as the REST endpoint as shown in the following image.

Firebase database URL

 

Step 2: Refer the HTTP package version in the pubspec.yaml file, which is located at the root of your project. Then, import the HTTP client package, in the main.dart file to use the HTTP client for retrieval of JSON data from the Firebase Realtime Database.

pubspec http dependencies

 

import 'package:http/http.dart' as http;

 

Step 3: Define an asynchronous future function (Say getJsonFromFirebaseRestAPI())in the main state class, in order to retrieve the JSON data string as response from the Firebase Database using their URL REST endpoint. All you need to do is append “.json” to the end of the URL and send get(url) request from the HTTPS client to retrieve the Firebase JSON data.

Future<String> getJsonFromFirebaseRestAPI() async {
  String url = "https://flutterdemo-f6d47.firebaseio.com/chartSalesData.json";
  http.Response response = await http.get(Uri.parse(url));
  return response.body;
}

 

Here, appended the chartSalesData.json to the end of the URL to retrieve the JSON chart sales data from the Firebase Database.

 

Conversion of retrieved Firebase JSON data to chart data list

 

Step 1: Create a custom class (Say SalesData), in which the chart data objects are stored and also define a factory constructor (say SalesData.fromJson(Map<String, dynamic> parsedJson)), which is used to parse a dynamic JSON object into the user object (SalesData).

class SalesData {
  SalesData(this.month, this.sales);
 
  final String month;
  final int sales;
 
  factory SalesData.fromJson(Map<String, dynamic> parsedJson) {
    return SalesData(
      parsedJson['month'].toString(),
      parsedJson['sales'],
    );
  }
}

 

Step 2: Inside the main state class, create a list of chart data type (say SalesData), in which the parsed data is to be stored and also define the loadSalesData() function, which handles the deserialization steps mentioned as follows are carried out.

 Deserialization steps:

  1. First, call the getJsonFromFirebaseRestAPI() function, which returns the retrieved JSON data string from the Firebase Database retrieved using the HTTP client.
  2. Decode the raw string you got from the first step using the json.decode() method.
  3. Deserialize the decoded JSON response by calling the SalesData.fromJson() constructor so that you can now use the SalesData object to access it entities.
    List<SalesData> chartData = []; 
     
    Future loadSalesData() async {
      String jsonString = await getJsonFromFirebaseRestAPI();
      final jsonResponse = json.decode(jsonString);
      setState(() {
        for (Map<String, dynamic> i in jsonResponse)
          chartData.add(SalesData.fromJson(i));
      });
    }
    

 

Step 3: Call the loadSalesData() method in the initState() method for loading the data at the start of the chart application.

@override
void initState() {
  loadSalesData();
  super.initState();
}

 

Step 4: Call the getJsonFromFirebase() method in the builder method of the FutureBuilder to load the chart data and return the chart if the snapshot data is not empty, otherwise return the CircularProgressIndicator to indicate that the data is loading.

FutureBuilder(
 future: getJsonFromFirebase(),
 builder: (context, snapShot) {
  if (snapShot.hasData) {
   return SfCartesianChart()
  }
  else{
   return CircularProgressIndicator();
  } 
 }
)
 

 

Step 5: Finally, initialize the SfCartesianChart with their necessary properties along with the chartData list as its data source in the build method.

SfCartesianChart(
  primaryXAxis: CategoryAxis(),
  title: ChartTitle(text: 'Half yearly sales analysis'),
  series: <ChartSeries<SalesData, String>>[
    LineSeries<SalesData, String>(
      dataSource: chartData,
      xValueMapper: (SalesData sales, _) => sales.month,
      yValueMapper: (SalesData sales, _) => sales.sales,
    )
  ]
)

 

Thus, the rendering of chart using the JSON data stored in the Firebase Database is done.

 

For further reference on accessing Firebase Realtime Database using the Firebase REST API and HTTP client, click here.

For further reference on Parsing JSON object in Flutter, click here.

 

View the sample in GitHub.

ADD COMMENT
You must log in to leave a comment

Please sign in to access our KB

This page will automatically be redirected to the sign-in page in 10 seconds.

Up arrow icon

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon

Live Chat Icon For mobile