如何在Flutter中基于Firestore存储的类别数据实现饼图展示
实现步骤
1. 前置依赖配置
首先取消你代码中cloud_firestore的注释,同时在pubspec.yaml中添加相关依赖:
dependencies: flutter: sdk: flutter pie_chart: ^最新适配版本 cloud_firestore: ^最新适配版本 firebase_core: ^最新适配版本
- 需先完成Flutter项目的Firebase初始化配置,在main函数中添加初始化逻辑:
void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(const MyApp()); }
2. 核心逻辑修改
你需要从Firestore拉取消费记录,按category字段分组统计每个类别的总金额,替换原来的静态dataMap即可。以下是完整修改后的代码(支持数据实时更新):
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; // 初始dataMap为空,后续从Firestore加载 Map<String, double> dataMap = {}; // 预设足够多的颜色适配不同数量的分类 List<Color> colorList = [ Colors.red, Colors.yellow, Colors.green, Colors.blue, Colors.purple, Colors.orange, Colors.pink, Colors.cyan ]; // 加载状态标记 bool isLoading = true; @override void initState() { super.initState(); _loadCategoryData(); } // 从Firestore拉取并统计分类数据 void _loadCategoryData() { // 替换为你自己的消费记录集合名称 FirebaseFirestore.instance.collection('你的消费集合名').snapshots().listen((snapshot) { Map<String, double> tempMap = {}; for (var doc in snapshot.docs) { String category = doc.get('category') ?? '其他'; // 替换为你自己的金额字段名,类型转成double double amount = (doc.get('amount') as num).toDouble(); // 累加同分类的金额 if (tempMap.containsKey(category)) { tempMap[category] = tempMap[category]! + amount; } else { tempMap[category] = amount; } } setState(() { dataMap = tempMap; isLoading = false; key++; // 刷新饼图 }); }, onError: (e) { setState(() { isLoading = false; }); debugPrint('加载数据失败:$e'); }); } Widget pieChartExampleOne(){ // 没有数据的时候显示提示 if (dataMap.isEmpty) { return const Text('暂无消费数据'); } 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: [ const SizedBox(height: 50,), isLoading ? const CircularProgressIndicator() : pieChartExampleOne(), ], ), ) ); } }
3. 注意事项
- 代码中的
你的消费集合名、amount字段需要替换为你Firestore里对应的实际集合、字段名称 - 如果不需要实时更新,把
snapshots().listen改成get()即可切换为一次性拉取数据的模式 - 如果分类数量超过预设的颜色列表长度,可自行扩展颜色列表,或者添加随机颜色生成逻辑
内容的提问来源于stack exchange,提问作者New user
相关产品推荐
相关产品推荐

