Articles in this section
Category / Section

How to render a Flutter chart using the JSON data (SfCartesianChart) ?

2 mins read

Using the deserialization concept, you can convert the JSON data to Dart list object and use that deserialized list object as chart data for Flutter Cartesian chart. The parsing of raw JSON data to dart object model is called deserialization.

Refer the following instructions, to convert JSON data to chart data list using the deserialization concept.

Step 1: First, create an assets folder in the project root directory, in which the .json file (say data.json) holding the data to be converted is to be stored.

assets folder creation JSON data file

 

Step 2: Specify the Json file (say data.json) asset in the pubspec.yaml file, located at the root of your project.

pubspec asset specification

 

Step 3: 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 user object (SalesData).

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

 

Step 4: 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 create a method loadSalesData(), which handles the deserialization steps mentioned as follows.

 Deserialization steps

  1. First, load the raw json string from the assets by calling the getJsonFromAssets() method which converts and returns the JSON file data available in assets folder in string format with the help of loadString() method of flutter services package.
  2. Decode the raw string that 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 SalesData object to access our entities.
    List<SalesData> chartData = [];
     
    Future<String> getJsonFromAssets() async {
        return await rootBundle.loadString('assets/data.json');
    }
     
    Future loadSalesData() async {
        final String jsonString = await getJsonFromAssets();
        final dynamic jsonResponse = json.decode(jsonString);
        for (Map<String, dynamic> i in jsonResponse) {
          chartData.add(SalesData.fromJson(i));
        }
    }
    

 

Step 5: 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 6: Call the getJsonFromAssets() method in the future 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 to the chart.

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

 

Step 7: Finally, initialize the SfCartesianChart with their necessary properties along with the chartData list as the 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 conversion of JSON data to chart data list is done.

 

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 render chart using the JSON data (SfCartesianChart).

You can refer to our Flutter Cartesian Chart feature tour
page to know about its other groundbreaking feature representations documentation
and how to quickly get started for configuration specifications.  You can also explore our Flutter Cartesian Chart example  to understand how to create and manipulate data.

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
Please sign in to leave a comment
Access denied
Access denied