Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
186 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

enter image description here

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...