Flutter 如何在Flatter中的Piechart中显示json对象?

Flutter 如何在Flatter中的Piechart中显示json对象?,flutter,dart,Flutter,Dart,这是我的JSON数据: dashboardResult:{ "new_call":18, "overdue_calls":0, "completed_calls":2523 } 现在我想在PieChart中以%显示这3个json对象值: 这是我用来显示图表的代码: Widget onTimeComp(BuildContext context) { return Container( margin: EdgeInsets.only(left: 10,

这是我的JSON数据:

dashboardResult:{
    "new_call":18,
    "overdue_calls":0,
    "completed_calls":2523
}
现在我想在PieChart中以%显示这3个json对象值: 这是我用来显示图表的代码:

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对象的值

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

您可以复制粘贴运行下面的完整代码
步骤1:将json字符串解析为对象,您可以在完整代码中看到
类DashboardResult
定义
步骤2:在解析后的
initState()
中,可以执行
dataMap.putIfAbsent(“Complete”,()=>dashboardResult.completedCalls.toDouble())

工作演示

完整代码

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,
            )),
          ],
        ),
      ]),
    );
  }
}
导入'dart:io';
进口“包装:颤振/基础.dart”;
进口“包装:颤振/材料.省道”;
导入“package:pie_chart/pie_chart.dart”;
//要解析此JSON数据,请执行以下操作
//
//最终dashboardResult=dashboardResultFromJson(jsonString);
导入“dart:convert”;
DashboardResult dashboardResultFromJson(字符串str)=>
DashboardResult.fromJson(json.decode(str));
字符串dashboardResultToJson(DashboardResult数据)=>
encode(data.toJson());
类仪表板结果{
int newCall;
int超负荷呼叫;
int completedCalls;
仪表板结果({
这个新电话,
这是我的电话,
这个,完成呼叫,
});
factory DashboardResult.fromJson(映射json)=>
仪表板结果(
newCall:json[“new_call”],
overdueCalls:json[“过期的_调用”],
completedCalls:json[“completed_calls”],
);
映射到JSON()=>{
“新呼叫”:新呼叫,
“过期电话”:过期电话,
“已完成的呼叫”:已完成的呼叫,
};
}
//为桌面设置平台覆盖以避免异常。看见
// https://flutter.dev/desktop#target-平台覆盖以获取更多信息。
void enablePlatformOverrideForDesktop(){
如果(!kIsWeb&&(Platform.isMacOS | | | Platform.isWindows | | Platform.isLinux)){
debugDefaultTargetPlatformOverride=TargetPlatform.fuchsia;
}
}
void main(){
enablePlatformOverrideForDesktop();
runApp(MyApp());
}
类MyApp扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
返回材料PP(
标题:“饼图演示”,
主题:主题数据(
原始样本:颜色。蓝灰色,
),
黑暗主题:主题数据(
原始样本:颜色。蓝灰色,
亮度:亮度。暗,
),
家:派(),
);
}
}
类Pie扩展了StatefulWidget{
@凌驾
_PieState createState()=>\u PieState();
}
类_PieState扩展了状态{
Map dataMap=Map();
列表颜色列表=[
颜色,红色,
颜色,绿色,
颜色,蓝色,
颜色,黄色,
];
字符串jsonString;
仪表板结果仪表板结果;
@凌驾
void initState(){
super.initState();
jsonString=''{
“新电话”:18,
“过期电话”:0,
“已完成的电话”:2523
}
''';
dashboardResult=dashboardResultFromJson(jsonString);
dataMap.putIfAbsent(
“Complete”,()=>dashboardResult.completedCalls.toDouble());
dataMap.putIfAbsent(“新调用”,()=>dashboardResult.newCall.toDouble());
dataMap.putIfAbsent(
“过期”,()=>dashboardResult.overdueCalls.toDouble());
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标题:文本(“饼图”),
),
主体:堆栈(
儿童:[
列表视图(
儿童:[
onTimeComp(上下文),
],
),
],
),
);
}
小部件onTimeComp(构建上下文){
返回容器(
边距:仅限边集(左:10,右:10,顶部:10,底部:5),
填充:仅限边集(顶部:15,底部:25,左侧:15,右侧:0),
颜色:颜色。浅蓝色[100],
子项:列(子项:[
划船(
儿童:[
容器(
子项:文本(“按时完成”,
样式:TextStyle(
颜色:Colors.lightBlue,fontwweight:fontwweight.bold),
),
],
),
大小盒子(
身高:20,
),
划船(
mainAxisAlignment:mainAxisAlignment.center,
儿童:[
容器(
孩子:皮查特(
dataMap:dataMap,
animationDuration:持续时间(毫秒:800),
chartLegendSpacing:32.0,
chartRadius:MediaQuery.of(context).size.width/2.7,
showChartValuesInPercentage:真,
showChartValues:正确,
showChartValuesOutside:false,
chartValueBackgroundColor:颜色.灰色[200],
颜色列表:颜色列表,
传奇:没错,
legendPosition:legendPosition.right,
小数位数:1,
showChartValueLabel:正确,
初始角度:0,
chartValueStyle:defaultChartValueStyle.copyWith(
颜色:Colors.blueGrey[900]。不透明度为(0.9)),
chartType:chartType.disc,
)),
],
),
]),
);
}
}
dataMap.putIfAbsent("Complete", () =>new_call);
dataMap.putIfAbsent("New Calls", () => overdue_calls);
dataMap.putIfAbsent("Overdue", () => completed_calls);
@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());
  }
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,
            )),
          ],
        ),
      ]),
    );
  }
}