如何在 Flutter 饼图中显示 JSON 数据?

How to show JSON Data in Pie Chart in Flutter?

我是 Flutter 新手。我想用 JSON 数据绘制饼图。我有一个 API 用于饼图数据。但我不知道 如何使用 API(使用 JSON 数据)开发饼图。你能帮我么。谢谢。

这是我的 API :

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

我想给你最简单易懂的方法,可以有很多方法,

  1. 首先需要在 dependencies 部分 dependencies 中导入一些包来请求和饼图 pubspec.yaml
  http: ^0.13.4
  pie_chart: ^5.1.0
  1. 现在您需要为您的 API 数据制作一个模型,我为您制作了它,但您可以通过 app.quicktype.io 制作它,它可以为您生成:
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. 现在你需要这样做,我稍微描述一下代码:
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 bacause 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,
            ),
          ),
        ),
      ),
    );
  }
}

你可以把这个文件的每个部分分开,但我把它们放在一起了


请记住,如果您使用的是 api,则需要将此行添加到 ./android/app/src/main 中的 AndroidManifest.xml 以访问互联网

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

舔得好 :)

只需使用这个插件pie_chart: ^5.1.0

import 'package:pie_chart/pie_chart.dart';

 Map<String, double> dataMap = {
        "highseverity": 990,
        "mediumseverity": 495,
        "lowseverity": 300,
        "warning": 100
    };

PieChart(dataMap: dataMap)