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

问题描述 投票:0回答:2

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

这是我的 API :

[
{
    "highseverity": 990,
    "mediumseverity": 495,
    "lowseverity": 300,
    "warning": 100
}
]
json flutter pie-chart
2个回答
0
投票

我想给你最简单易懂的方法,可以有很多方法来做到这一点,

  1. 首先需要导入一些包来请求和饼图在
    pubspec.yaml
    dependencies
    部分
  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,
  });
}

我建议在

lib > models > severity.dart
中制作文件并粘贴。

  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 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,
            ),
          ),
        ),
      ),
    );
  }
}

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


请记住,如果您使用 api,则需要将此行添加到

AndroidManifest.xml
中的
./android/app/src/main
以访问互联网

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

好舔:)


0
投票

只需使用这个插件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)
© www.soinside.com 2019 - 2024. All rights reserved.