如何在饼图中显示json对象的抖动? [英] How to show json object in Piechart in flutter?

查看:35
本文介绍了如何在饼图中显示json对象的抖动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的JSON数据:

  dashboardResult:{"new_call":18,"overdue_calls":0,"completed_calls":2523} 

现在,我想在PieChart中以百分比显示这3个json对象值:

完整代码

  import'dart:io';导入'package:flutter/foundation.dart';导入'package:flutter/material.dart';导入'package:pie_chart/pie_chart.dart';//要解析此JSON数据,请执行////最终的dashboardResult = dashboardResultFromJson(jsonString);导入'dart:convert';DashboardResultdashboardResultFromJson(String str)=>DashboardResult.fromJson(json.decode(str));字符串dashboardResultToJson(DashboardResult数据)=>json.encode(data.toJson());类DashboardResult {int newCall;int过期电话;int completeCalls;DashboardResult({this.newCall,this.overdueCalls,this.completedCalls,});factory DashboardResult.fromJson(Map< String,dynamic> json)=>DashboardResult(newCall:json ["new_call"],overdueCalls:json ["overdue_calls"],completedCalls:json ["completed_calls"],);Map< String,dynamic>toJson()=>{"new_call":newCall,"overdue_calls":overdueCalls,"completed_calls":completedCalls,};}//为桌面设置平台替代以避免异常.看//https://flutter.dev/desktop#target-platform-override了解更多信息.无效enablePlatformOverrideForDesktop(){if(!kIsWeb&(Platform.isMacOS || Platform.isWindows || Platform.isLinux)){debugDefaultTargetPlatformOverride = TargetPlatform.fuchsia;}}void main(){enablePlatformOverrideForDesktop();runApp(MyApp());}MyApp类扩展了StatelessWidget {@override窗口小部件build(BuildContext context){返回MaterialApp(标题:饼图演示",主题:ThemeData(primarySwatch:Colors.blueGrey,),darkTheme:ThemeData(primarySwatch:Colors.blueGrey,亮度:亮度.暗,),主页:Pie(),);}}Pie类扩展了StatefulWidget {@override_PieState createState()=>_PieState();}类_PieState扩展了State< Pie>{Map< String,double>dataMap = Map();列表<颜色>colorList = [颜色,红色,颜色.绿色颜色.蓝色,颜色.黄色];字符串jsonString;DashboardResultdashboardResult;@override无效的initState(){super.initState();jsonString ='''{"new_call":18,"overdue_calls":0,"completed_calls":2523}''';dashboardResult = dashboardResultFromJson(jsonString);dataMap.putIfAbsent("Complete",()=>consoleResult.completedCalls.toDouble());dataMap.putIfAbsent("New Calls",()=> dashboardResult.newCall.toDouble());dataMap.putIfAbsent(过期",()=>consoleResult.overdueCalls.toDouble());}@override窗口小部件build(BuildContext context){返回脚手架(appBar:AppBar(标题:Text(饼图"),),身体:堆栈(子代:< Widget> [列表显示(子代:< Widget> [onTimeComp(context),],),],),);}窗口小部件onTimeComp(BuildContext context){返回容器(边距:EdgeInsets.only(左:10,右:10,上:10,下:5),填充:EdgeInsets.only(顶部:15,底部:25,左侧:15,右侧:0),颜色:Colors.lightBlue [100],child:Column(children:< Widget> [排(子代:< Widget> [容器(子级:Text(按时完成",样式:TextStyle(color:Colors.lightBlue,fontWeight:FontWeight.bold)),),],),SizedBox(高度:20,),排(mainAxisAlignment:MainAxisAlignment.center,子代:< Widget> [容器(孩子:PieChart(dataMap:dataMap,animationDuration:持续时间(毫秒:800),chartLegendSpacing:32.0,chartRadius:MediaQuery.of(context).size.width/2.7,showChartValuesInPercentage:true,showChartValues:true,showChartValuesOutside:否,chartValueBackgroundColor:Colors.grey [200],colorList:colorList,showLegends:是的,legendPosition:LegendPosition.right,小数位数:1showChartValueLabel:是的,initialAngle:0,chartValueStyle:defaultChartValueStyle.copyWith(color:Colors.blueGrey [900] .withOpacity(0.9)),chartType:ChartType.disc,)),],),]),);}} 

This is my JSON data:

dashboardResult:{
    "new_call":18,
    "overdue_calls":0,
    "completed_calls":2523
}

Now I want to show these 3 json object value in % in PieChart:see here is piechar This is my code to show PieChart:

Widget onTimeComp(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(left: 10, right:10, top:10, bottom:5),
      padding: EdgeInsets.only(top: 15,bottom: 25,left: 15,right: 0),
      color: Colors.lightBlue[100],
      child: Column(
          children: <Widget>[
            Row(
              children: <Widget>[
                Container(
                  child:Text("On-time Completion",style: TextStyle(color: Colors.lightBlue,fontWeight: FontWeight.bold)),
                ),
              ],
            ),
            SizedBox(height: 20,),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  child: PieChart(
                    dataMap: dataMap,
                    animationDuration: Duration(milliseconds: 800),
                    chartLegendSpacing: 32.0,
                    chartRadius: MediaQuery.of(context).size.width / 2.7,
                    showChartValuesInPercentage: true,
                    showChartValues: true,
                    showChartValuesOutside: false,
                    chartValueBackgroundColor: Colors.grey[200],
                    colorList: colorList,
                    showLegends: true,
                    legendPosition: LegendPosition.right,
                    decimalPlaces: 1,
                    showChartValueLabel: true,
                    initialAngle: 0,
                    chartValueStyle: defaultChartValueStyle.copyWith(color: Colors.blueGrey[900].withOpacity(0.9)),
                    chartType: ChartType.disc,
                    )
                ),
              ],
            ),
          ]
      ),
    );
  }

I called this method in body():

body: Stack(
        children: <Widget>[
          ListView(
            children: <Widget>[
              onTimeComp(context),
              ],
          ),
        ],
      ),
   ),

here is intState method:

@override
  void initState() {
    super.initState();
    dataMap.putIfAbsent("Complete", () =>2522 );
    dataMap.putIfAbsent("New Calls", () => 19);
    dataMap.putIfAbsent("Overdue", () => 0);
    }

Now how to show json objects value?

dataMap.putIfAbsent("Complete", () =>new_call);
dataMap.putIfAbsent("New Calls", () => overdue_calls);
dataMap.putIfAbsent("Overdue", () => completed_calls);

解决方案

You can copy paste run full code below
Step 1 : parse your json string to object, you can see class DashboardResult definition in full code
Step 2 : in initState() after parse , you can do dataMap.putIfAbsent("Complete", () => dashboardResult.completedCalls.toDouble());

@override
  void initState() {
    super.initState();

    jsonString = '''{
      "new_call":18,
    "overdue_calls":0,
    "completed_calls":2523
    }
    ''';

    dashboardResult = dashboardResultFromJson(jsonString);
    dataMap.putIfAbsent(
        "Complete", () => dashboardResult.completedCalls.toDouble());
    dataMap.putIfAbsent("New Calls", () => dashboardResult.newCall.toDouble());
    dataMap.putIfAbsent(
        "Overdue", () => dashboardResult.overdueCalls.toDouble());
  }

working demo

full code

import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:pie_chart/pie_chart.dart';
// To parse this JSON data, do
//
//     final dashboardResult = dashboardResultFromJson(jsonString);

import 'dart:convert';

DashboardResult dashboardResultFromJson(String str) =>
    DashboardResult.fromJson(json.decode(str));

String dashboardResultToJson(DashboardResult data) =>
    json.encode(data.toJson());

class DashboardResult {
  int newCall;
  int overdueCalls;
  int completedCalls;

  DashboardResult({
    this.newCall,
    this.overdueCalls,
    this.completedCalls,
  });

  factory DashboardResult.fromJson(Map<String, dynamic> json) =>
      DashboardResult(
        newCall: json["new_call"],
        overdueCalls: json["overdue_calls"],
        completedCalls: json["completed_calls"],
      );

  Map<String, dynamic> toJson() => {
        "new_call": newCall,
        "overdue_calls": overdueCalls,
        "completed_calls": completedCalls,
      };
}

// Sets a platform override for desktop to avoid exceptions. See
// https://flutter.dev/desktop#target-platform-override for more info.
void enablePlatformOverrideForDesktop() {
  if (!kIsWeb && (Platform.isMacOS || Platform.isWindows || Platform.isLinux)) {
    debugDefaultTargetPlatformOverride = TargetPlatform.fuchsia;
  }
}

void main() {
  enablePlatformOverrideForDesktop();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Pie Chart Demo',
      theme: ThemeData(
        primarySwatch: Colors.blueGrey,
      ),
      darkTheme: ThemeData(
        primarySwatch: Colors.blueGrey,
        brightness: Brightness.dark,
      ),
      home: Pie(),
    );
  }
}

class Pie extends StatefulWidget {
  @override
  _PieState createState() => _PieState();
}

class _PieState extends State<Pie> {
  Map<String, double> dataMap = Map();

  List<Color> colorList = [
    Colors.red,
    Colors.green,
    Colors.blue,
    Colors.yellow,
  ];
  String jsonString;
  DashboardResult dashboardResult;

  @override
  void initState() {
    super.initState();

    jsonString = '''{
      "new_call":18,
    "overdue_calls":0,
    "completed_calls":2523
    }
    ''';

    dashboardResult = dashboardResultFromJson(jsonString);
    dataMap.putIfAbsent(
        "Complete", () => dashboardResult.completedCalls.toDouble());
    dataMap.putIfAbsent("New Calls", () => dashboardResult.newCall.toDouble());
    dataMap.putIfAbsent(
        "Overdue", () => dashboardResult.overdueCalls.toDouble());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Pie Chart"),
      ),
      body: Stack(
        children: <Widget>[
          ListView(
            children: <Widget>[
              onTimeComp(context),
            ],
          ),
        ],
      ),
    );
  }

  Widget onTimeComp(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 5),
      padding: EdgeInsets.only(top: 15, bottom: 25, left: 15, right: 0),
      color: Colors.lightBlue[100],
      child: Column(children: <Widget>[
        Row(
          children: <Widget>[
            Container(
              child: Text("On-time Completion",
                  style: TextStyle(
                      color: Colors.lightBlue, fontWeight: FontWeight.bold)),
            ),
          ],
        ),
        SizedBox(
          height: 20,
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
                child: PieChart(
              dataMap: dataMap,
              animationDuration: Duration(milliseconds: 800),
              chartLegendSpacing: 32.0,
              chartRadius: MediaQuery.of(context).size.width / 2.7,
              showChartValuesInPercentage: true,
              showChartValues: true,
              showChartValuesOutside: false,
              chartValueBackgroundColor: Colors.grey[200],
              colorList: colorList,
              showLegends: true,
              legendPosition: LegendPosition.right,
              decimalPlaces: 1,
              showChartValueLabel: true,
              initialAngle: 0,
              chartValueStyle: defaultChartValueStyle.copyWith(
                  color: Colors.blueGrey[900].withOpacity(0.9)),
              chartType: ChartType.disc,
            )),
          ],
        ),
      ]),
    );
  }
}

这篇关于如何在饼图中显示json对象的抖动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆