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 a Flutter chart using the JSON data (SfCartesianChart) ?

Platform: Flutter |
Control: SfCartesianChart |
Published Date: July 2, 2020 |
Last Revised Date: May 18, 2021

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: <ChartSeries<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

ADD COMMENT
You must log in to leave a comment
Comments
Arpit Shrotriya
Jul 22, 2021

[ERROR:flutter/lib/ui/ui_dart_state.cc(207)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>'

Hello,

I am finding this error again and again in my code. Please Help

Reply
ferry farhanudin
Sep 02, 2021

how if data json "data": [ { "data": [ { "data": [ { "value": [ { "key": "1", "value": 2500 } ] } ] } ] } ]

Reply
Sriram Kiran Senthilkumar [Syncfusion]
Sep 02, 2021

Hi Ferry farhanudi,

We have analyzed your scenario at our end, and we have created a simple chart sample in which we have parsed the provided nested JSON structure and used the parsed data to render the chart widget. We have attached the sample below for your reference.

Sample: https://www.syncfusion.com/downloads/support/forum/168522/ze/f168522_jsonparsing1438195217

Please check with above-attached sample and revert us if you require further assistance.

Regards, Sriram Kiran

Felipe Werlang
Sep 08, 2021

Please, how if data json:

{ "chart":[ { "this_month_day":1, "this_month_order":"107.02", "last_month_day":3, "last_month_order":"215.69" }, { "this_month_day":2, "this_month_order":"977.81", "last_month_day":4, "last_month_order":"306.32" }, { "this_month_day":3, "this_month_order":"990.29", "last_month_day":5, "last_month_order":"999.83" } ] }

Reply
Sriram Kiran Senthilkumar [Syncfusion]
Sep 09, 2021

Hi Ferry farhanudi,

We have analyzed your query at our end, and we have created a simple chart sample in which we have parsed the provided JSON structure and used that parsed data to render the chart widget. We have attached the sample below for your reference.

Sample: https://www.syncfusion.com/downloads/support/directtrac/general/ze/KBjsonparsing-992530615

Please check with above-attached sample and revert us if you require further assistance.

  • Sriram Kiran
Shani
Oct 05, 2021

Please, how if data json:

{ { "EmotionCategory" : "happy", "Time" : "20:00:00" }, { "EmotionCategory" : "happy", "Time" : "20:10:00" }, { "EmotionCategory" : "happy", "Time" : "20:20:00" }, { "EmotionCategory" : "happy", "Time" : "20:30:00" }, { "EmotionCategory" : "happy", "Time" : "20:40:00" }, { "EmotionCategory" : "happy", "Time" : "20:50:00" }, { "EmotionCategory" : "neutral", "Time" : "21:00:00" }, { "EmotionCategory" : "neutral", "Time" : "21:10:00" }, { "EmotionCategory" : "neutral", "Time" : "21:20:00" }, { "EmotionCategory" : "neutral", "Time" : "21:30:00" }, { "EmotionCategory" : "neutral", "Time" : "21:40:00" }, { "EmotionCategory" : "neutral", "Time" : "21:50:00" }, { "EmotionCategory" : "happy", "Time" : "22:00:00" }, { "EmotionCategory" : "happy", "Time" : 22:10:00 }, { "EmotionCategory" : "happy", "Time" : 22:20:00 }, {

    "EmotionCategory" : "happy",
    "Time" : 22:30:00
 },
 {
    "EmotionCategory" : "happy",
    "Time" : 22:40:00
 },
 {
    "EmotionCategory" : "happy",
    "Time" : 22:50:00
 }

}

Reply
Sriram Kiran Senthilkumar [Syncfusion]
Oct 06, 2021

Hi Shani,

Greetings from Syncfusion. We have analyzed your query regarding to render the chart with the provided JSON string and we kindly request you to share us with more information regarding your chart rendering requirement because from the provided JSON data string, we found that there are two values that can be retrieved from, which are the Emotioncategory value which is of type string and the Time value which is of type DateTime. Due to this value types, we are not sure on which of these values needs to be mapped for x and y axis respectively and so kindly please revert us with the requested information regarding which of these field's values are to be mapped for x and y value mapper respectively so that it will be helpful in providing the solutions sooner.

Regards, Sriram Kiran

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