Articles in this section
Category / Section

How to render the Flutter Chart using JSON data stored in Firebase database?

5 mins read

eineUsing 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: <LineSeries<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.


Conclusion

I hope you enjoyed learning about how to to render the Flutter Chart using JSON data stored in Firebase database.

You can refer to our Flutter Cartesian Chart feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications.

For current customers, you can check out our 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 other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied