Search code examples
jsonflutterpie-chart

How to show JSON Data in Pie Chart in Flutter?


I am new in Flutter. I want to draw a pie chart with the JSON data. I have one API for pie chart data. But I do not know How to Develop a Pie Chart using that API(using JSON Data). Can you Please Help me. Thank you.

Here is the My API :

[
{
    "highseverity": 990,
    "mediumseverity": 495,
    "lowseverity": 300,
    "warning": 100
}
]

Solution

  • i want to give you the easiest and understandable way it can be many ways to do it,

    1. First need to import some packages to request and for piechart in pubspec.yaml in dependencies section
      http: ^0.13.4
      pie_chart: ^5.1.0
    
    1. now you need to make a model for your API data, i made it for you but you can make it by app.quicktype.io it can generate for you:
    class Severity {
      int highseverity;
      int mediumseverity;
      int lowseverity;
      int warning;
    
      Severity({
        required this.highseverity,
        required this.mediumseverity,
        required this.lowseverity,
        required this.warning,
      });
    }
    

    i suggest to make file in lib > models > severity.dart and paste in.

    1. now you need to do like this, I describe codes a little:
    import 'package:http/http.dart' as http;
    import 'package:pie_chart/pie_chart.dart';
    import 'dart:convert' as convert;
    import 'models/severity.dart';
    
    class Home extends StatefulWidget {
      const Home({Key? key}) : super(key: key);
    
      @override
      _HomeState createState() => _HomeState();
    }
    
    class _HomeState extends State<Home> {
      List<Severity> dataList = []; // list of api data
    
      getResponse() async {
    
        var url = ""; // your URL must be paste here, it's required
    
        await http.get(Uri.parse(url)).then(
          // this get data from api you entered
          (value) {
            if (dataList.isEmpty) {
              // if list is empty to avoid repetitive data
              if (value.statusCode == 200) {
                // if status of request was ok will continue
                List jsonList = convert
                    .jsonDecode(value.body); // this like convert json to list
                if (jsonList.isNotEmpty) {
                  // if jsonList wasnt empty which means had data will make data for each json object
                  for (var i = 0; i < jsonList.length; i++) {
                    setState(() {
                      dataList.add(
                        Severity(
                          highseverity: jsonList[i]["highseverity"],
                          mediumseverity: jsonList[i]["mediumseverity"],
                          lowseverity: jsonList[i]["lowseverity"],
                          warning: jsonList[i]["warning"],
                        ),
                      );
                    });
                  }
                } else {
                  dataList.add(
                    /// if couldnt catch data, this will make one entry of zero data
                    Severity(
                      highseverity: 0,
                      mediumseverity: 0,
                      lowseverity: 0,
                      warning: 0,
                    ),
                  );
                }
              }
            }
          },
        );
      }
    
      // this will make state when app runs
      @override
      void initState() {
        getResponse();
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        // this is a map of data because piechart need a map
        Map<String, double> dataMap = {
          'highseverity':
              dataList.isNotEmpty ? dataList[0].highseverity.toDouble() : 0,
          "mediumseverity":
              dataList.isNotEmpty ? dataList[0].mediumseverity.toDouble() : 0,
          "lowseverity":
              dataList.isNotEmpty ? dataList[0].lowseverity.toDouble() : 0,
          "warning": dataList.isNotEmpty ? dataList[0].warning.toDouble() : 0,
        };
        // -----------------------
        return Scaffold(
          body: Center(
            child: Padding(
              padding: const EdgeInsets.all(15.0),
              // this is your chart, you can edit it as you like
              child: PieChart(
                dataMap: dataMap, // this need to be map for piechart
                animationDuration: const Duration(milliseconds: 800),
                chartLegendSpacing: 32,
                initialAngleInDegree: 0,
                chartType: ChartType.disc,
                ringStrokeWidth: 32,
                legendOptions: const LegendOptions(
                  showLegendsInRow: false,
                  legendPosition: LegendPosition.right,
                  showLegends: true,
                ),
                chartValuesOptions: const ChartValuesOptions(
                  showChartValueBackground: true,
                  showChartValues: true,
                  showChartValuesOutside: false,
                  decimalPlaces: 1,
                ),
              ),
            ),
          ),
        );
      }
    }
    

    You can seprate each part of this file as you like but i put them together


    remember if you are using api you need to add this lines to your AndroidManifest.xml in ./android/app/src/main to access internet

    <manifest xmlns:android="...">
      <uses-permission android:name="android.permission.INTERNET"/> <!-- Add this line-->
    </manifest> 
    

    good lick :)