如何从扑火商店开发饼图 [英] How to developed pie chart from firestore in flutter

查看:14
本文介绍了如何从扑火商店开发饼图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手,我想制作饼图,但它必须显示存储在Firestore中的类别。如何显示基于存储在FireStore中的类别的饼图?有人能帮上忙吗?谢谢

在这段代码中,我仍然使用示例数据来存储饼图。我想根据存储在FireStore中的数据更改它。

代码

import 'package:flutter/material.dart';
import 'package:pie_chart/pie_chart.dart';
//import 'package:cloud_firestore/cloud_firestore.dart';

class StatisticsExpense extends StatefulWidget {
  @override
  _StatisticsExpenseState createState() => _StatisticsExpenseState();
}

class _StatisticsExpenseState extends State<StatisticsExpense> {

  int key = 0;

  Map<String, double> dataMap = {
    "Food": 5,
    "Health": 3,
    "Social Life": 2,

  };

  List<Color> colorList = [
    Colors.red,
    Colors.yellow,
    Colors.green,
  ];

  Widget pieChartExampleOne(){
    return PieChart(
      key: ValueKey(key),
      dataMap: dataMap,
      initialAngleInDegree: 0,
      animationDuration: Duration(milliseconds: 2000),
      chartType: ChartType.ring,
      chartRadius: MediaQuery.of(context).size.width / 3.2,
      ringStrokeWidth: 32,
      colorList: colorList,
      chartLegendSpacing: 32,
      chartValuesOptions: ChartValuesOptions(
        showChartValuesOutside: true,
        showChartValuesInPercentage: true,
        showChartValueBackground: true,
        showChartValues: true,
        chartValueStyle: TextStyle(
          fontWeight: FontWeight.bold,
          color: Colors.black
        )
      ),
      centerText: 'Expense',
      legendOptions: LegendOptions(
        showLegendsInRow: false,
        showLegends: true,
        legendShape: BoxShape.rectangle,
        legendPosition: LegendPosition.right,
        legendTextStyle: TextStyle(
          fontWeight: FontWeight.bold,
          color: Colors.black,
        )
      ),
    );
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            SizedBox(height: 50,),
            pieChartExampleOne(),
          ],
        ),
      )
    );
  }
}

推荐答案

我希望您已经在Ffltter项目中完成了基本的Firebase设置。

首先,创建费用模型:

class Expense {
  String amount;
  String category;
  String date;
  String description;

  Expense(
      {required this.amount,
      required this.category,
      required this.date,
      required this.description});
}

创建获取类别映射及其计数的方法

late List<Expense> _expense = [];

  Map<String, double> getCategoryData() {
    Map<String, double> catMap = {};
    for (var item in _expense) {
      print(item.category);
      if (catMap.containsKey(item.category) == false) {
        catMap[item.category] = 1;
      } else {
        catMap.update(item.category, (int) => catMap[item.category]! + 1);
        // test[item.category] = test[item.category]! + 1;
      }
      print(catMap);
    }
    return catMap;
  }

然后创建一个流以获取Firbase集合:

final Stream<QuerySnapshot> expStream =
        FirebaseFirestore.instance.collection('TransactionExpense').snapshots();

使用";StreamBuilder";扭曲Pichart小部件并设置流:

StreamBuilder<Object>(
  stream: expStream,
  builder: (context, snapshot) {
    if (snapshot.hasError) {
       return Text("something went wrong");
    }
    if (snapshot.connectionState == ConnectionState.waiting) {
       return CircularProgressIndicator();
    }
    final data = snapshot.requireData;
    print("Data: $data");
    getExpfromSanapshot(data);
    return pieChartExampleOne();
  },
),

创建将快照数据转换为元素列表的方法:

void getExpfromSanapshot(snapshot) {
  if (snapshot.docs.isNotEmpty) {
    _expense = [];
    for (int i = 0; i < snapshot.docs.length; i++) {
      var a = snapshot.docs[i];
      // print(a.data());
      Expense exp = Expense.fromJson(a.data());
      _expense.add(exp);
      // print(exp);
     }
   }
}

通过这样做,您可以获取FireStore数据并将其绘制在Pichat中,并且这将是实时的(由于StreamBuilder,只要数据更新到Firebase,Pichart就会立即更新)

完整代码:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:pie_chart/pie_chart.dart';

class StatisticsExpense extends StatefulWidget {
  @override
  _StatisticsExpenseState createState() => _StatisticsExpenseState();
}

class _StatisticsExpenseState extends State<StatisticsExpense> {
  int key = 0;

  late List<Expense> _expense = [];

  Map<String, double> getCategoryData() {
    Map<String, double> catMap = {};
    for (var item in _expense) {
      print(item.category);
      if (catMap.containsKey(item.category) == false) {
        catMap[item.category] = 1;
      } else {
        catMap.update(item.category, (int) => catMap[item.category]! + 1);
        // test[item.category] = test[item.category]! + 1;
      }
      print(catMap);
    }
    return catMap;
  }

  List<Color> colorList = [
    Color.fromRGBO(82, 98, 255, 1),
    Color.fromRGBO(46, 198, 255, 1),
    Color.fromRGBO(123, 201, 82, 1),
    Color.fromRGBO(255, 171, 67, 1),
    Color.fromRGBO(252, 91, 57, 1),
    Color.fromRGBO(139, 135, 130, 1),
  ];

  Widget pieChartExampleOne() {
    return PieChart(
      key: ValueKey(key),
      dataMap: getCategoryData(),
      initialAngleInDegree: 0,
      animationDuration: Duration(milliseconds: 2000),
      chartType: ChartType.ring,
      chartRadius: MediaQuery.of(context).size.width / 3.2,
      ringStrokeWidth: 32,
      colorList: colorList,
      chartLegendSpacing: 32,
      chartValuesOptions: ChartValuesOptions(
          showChartValuesOutside: true,
          showChartValuesInPercentage: true,
          showChartValueBackground: true,
          showChartValues: true,
          chartValueStyle:
              TextStyle(fontWeight: FontWeight.bold, color: Colors.black)),
      centerText: 'Expense',
      legendOptions: LegendOptions(
          showLegendsInRow: false,
          showLegends: true,
          legendShape: BoxShape.rectangle,
          legendPosition: LegendPosition.right,
          legendTextStyle: TextStyle(
            fontWeight: FontWeight.bold,
            color: Colors.black,
          )),
    );
  }

  @override
  Widget build(BuildContext context) {
    final Stream<QuerySnapshot> expStream =
        FirebaseFirestore.instance.collection('TransactionExpense').snapshots();

    void getExpfromSanapshot(snapshot) {
      if (snapshot.docs.isNotEmpty) {
        _expense = [];
        for (int i = 0; i < snapshot.docs.length; i++) {
          var a = snapshot.docs[i];
          // print(a.data());
          Expense exp = Expense.fromJson(a.data());
          _expense.add(exp);
          // print(exp);
        }
      }
    }

    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SizedBox(
              height: 50,
            ),
            StreamBuilder<Object>(
              stream: expStream,
              builder: (context, snapshot) {
                if (snapshot.hasError) {
                  return Text("something went wrong");
                }
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return CircularProgressIndicator();
                }
                final data = snapshot.requireData;
                print("Data: $data");
                getExpfromSanapshot(data);
                return pieChartExampleOne();
              },
            ),
          ],
        ),
      ),
    );
  }
}

class Expense {
  String amount;
  String category;
  String date;
  String description;

  Expense(
      {required this.amount,
      required this.category,
      required this.date,
      required this.description});

  factory Expense.fromJson(Map<String, dynamic> json) {
    return Expense(
      amount: json['amount'],
      category: json['category'],
      date: json['date'],
      description: json['description'],
    );
  }
}

// Sample data for PiChart
Map<String, double> dataMap = {
  "Food": 4,
  "Health": 3,
  "Social Life": 2,
};

// Sample data for Expense list
List<Expense> getExpenseList() {
  final List<Expense> chartData = [
    Expense(
        amount: "RM100",
        category: "Food",
        date: "Jan 15, 2021",
        description: "Break fast"),
    Expense(
        amount: "RM200",
        category: "Health",
        date: "Feb 15, 2021",
        description: "Workout"),
    Expense(
        amount: "RM200",
        category: "Health",
        date: "Feb 15, 2021",
        description: "Workout"),
    Expense(
        amount: "RM45",
        category: "Health",
        date: "Feb 25, 2021",
        description: "Workout"),
    Expense(
        amount: "RM80",
        category: "Social Life",
        date: "Feb 26, 2021",
        description: "Social Media"),
  ];
  return chartData;
}

这篇关于如何从扑火商店开发饼图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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