You need to enable JavaScript to run this app. Flutter中新增预算时如何更新Firestore同分类金额并同步到ListView
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中新增预算时如何更新Firestore同分类金额并同步到ListView

Flutter 同分类同币种预算金额合并实现方案

问题描述

我是Flutter开发新手,目前已经实现预算新增功能,可将数据存储到Firebase Firestore,也能拉取数据到ListView展示。现在需要实现每个分类仅展示一条列表,相同币种的预算金额自动累加:当用户新增同一分类的预算时,金额自动计算合并后更新到ListView中。

Firebase数据结构
期望效果:食品类预算合并为一条,总金额为IDR 160


预算分类选择页代码

import 'package:flutter/material.dart';
import 'package:monger_app/localization/localization_constants.dart';
import 'package:monger_app/page/detail.dart';
import 'package:monger_app/theme/colors.dart';

class BudgetSettings extends StatefulWidget {
  @override
  _BudgetSettingsState createState() => _BudgetSettingsState();
}

class _BudgetSettingsState extends State<BudgetSettings> {
  List<Container> categorylist = new List();

  var character=[
    {"name":"Food", "image":"food.png"},
    {"name":"Social-Life", "image":"travel.png"},
    {"name":"Transportation", "image":"transportation.png"},
    {"name":"Beauty", "image":"makeup.png"},
    {"name":"Household", "image":"household.png"},
    {"name":"Education", "image":"education.png"},
    {"name":"Health", "image":"health.png"},
    {"name":"Gift", "image":"gift.png"},
    {"name":"Other", "image":"other.png"},
  ];
  _makelist() async {
    for (var i = 0; i < character.length; i++) {
      final newcharacter = character[i];
      final String image = newcharacter["image"];
      categorylist.add(
        new Container(
          padding: new EdgeInsets.all(20.0),
          child: new Card( child:
              SingleChildScrollView(
                child: new Column(
                      children: <Widget>[
                        new Hero(
                          tag: newcharacter['name'], 
                          child: new Material(
                            child: new InkWell(
                              onTap: ()=> Navigator.of(context).push(new MaterialPageRoute(
                                builder: (BuildContext context)=> new Detail(name: newcharacter['name'], image: image,),

                              )),
                                child:
                                  new Image.asset("assets/$image", fit: BoxFit.contain,),
                                )
                              ),
                              ),

                        new Padding(padding: new EdgeInsets.all(5.0),),
                        new Text(newcharacter['name'], style: new TextStyle(fontSize: 18.0),),
                      ],
                    ),
              ),
            ),
            ),
      );
    }
  }

  @override
  void initState() {
    _makelist();
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: primary,
        title: Text(getTranslated((context), "budget_settings"),

      ),),

      body: new GridView.count(
          crossAxisCount: 2,
          children: categorylist,
      ),
    );
  }
}

新增预算页代码

import 'package:dropdownfield/dropdownfield.dart';
import 'package:flutter/material.dart';
import 'package:monger_app/localization/localization_constants.dart';
import 'package:monger_app/page/account.dart';
import 'package:monger_app/page/budgetsettings.dart';
import 'package:monger_app/theme/colors.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';

class Detail extends StatefulWidget {


  Detail({this.name, this.image});
  final String name;
  final String image;

  @override
  _DetailState createState() => _DetailState();
}

class _DetailState extends State<Detail> {
  @override

  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text(getTranslated((context), "budget_settings"),),
        elevation: 0,
        brightness: Brightness.light,
        backgroundColor: primary,
        leading: IconButton(
          onPressed: (){
            Navigator.pop(context, MaterialPageRoute(builder: (context) => Account()));
          },
          icon: Icon(Icons.arrow_back_ios,
            size: 20,
            color: Colors.black,),
        ),
      ),
      body: new ListView(
        children: <Widget>[
          new Container(
              height: 250.0,
              child:
              new Hero(tag: widget.name,
                  child: new Material(
                      child: new InkWell(
                        child: new Image.asset("assets/${widget.image}", fit: BoxFit.contain,),
                      )
                  ))
          ),
          new Name(name: widget.name,),
        ],
      ),
    );
  }
}

class Name extends StatefulWidget {
  Name({this.name});
  final String name;

  @override
  _NameState createState() => _NameState();
}

class _NameState extends State<Name> {
  @override
  String selectCurrency;

  final currencySelected = TextEditingController();
  var _formKey = GlobalKey<FormState>();


  List <String> currencycategories = [
    "IDR",
    "MYR",
    "USD",
    "CNY"
  ];
  Widget build(BuildContext context) {
    final amount = TextEditingController();
    FirebaseFirestore firestore = FirebaseFirestore.instance;
    CollectionReference collect= firestore.collection("Budget");

    final FirebaseAuth _auth = FirebaseAuth.instance;
    final User user =_auth.currentUser;
    final uid = user.uid;

    return Form(
        key: _formKey,
        child: Padding(
          padding: EdgeInsets.all(20.0),
          child: Column(
            children: <Widget>[
              Container(
                  child: Center(
                    child: Column(
                      children: <Widget>[
                        Padding(
                          padding: EdgeInsets.all(20.0),
                          child: Text(
                            widget.name,
                            textAlign: TextAlign.center,
                            style: new TextStyle(
                              fontSize: 25.0,
                              color: primary,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        Row(
                          children: <Widget> [
                            new Expanded(child: new DropDownField(
                              controller: currencySelected,
                              labelText: getTranslated((context), "currency_hint"),
                              enabled: true,
                              itemsVisibleInDropdown: 4,
                              items: currencycategories,
                              onValueChanged: (dynamic value) {
                                selectCurrency = value;
                              },
                              value: selectCurrency,
                              required: false,
                            ),
                              flex: 2,
                            ),
                            new SizedBox(
                              width: 10.0,
                            ),
                            new Expanded(child: TextFormField(
                              validator: (input) {
                                if (input.isEmpty) return 'Please fill up the text fields';
                              },
                              controller: amount,
                              decoration: InputDecoration(
                                border: OutlineInputBorder(),
                                labelText: getTranslated((context), "budget_enter"),
                                enabledBorder: OutlineInputBorder(

                                  borderSide: BorderSide(color: secondary),
                                ),
                                focusedBorder: OutlineInputBorder(
                                  borderSide: BorderSide(color: secondary),
                                ),
                              ),
                            ),
                              flex: 2,
                            )],
                        ),
                        Padding(
                          padding: EdgeInsets.all(20.0),
                          child: ElevatedButton(

                            onPressed: () async {
                              final FirebaseAuth _auth = FirebaseAuth
                                  .instance;
                              final User user = _auth.currentUser;
                              final uid = user.uid;

                              if(!_formKey.currentState.validate()){
                                return;
                              }
                              _formKey.currentState.save();

                              collect.add({
                                'name': this.widget.name,
                                'currency': selectCurrency,
                                'amount': amount.text,
                              });
                              amount.text = "";
                              Navigator.pop(context);
                            },
                            child: Text(getTranslated((context), "save_button").toUpperCase(), style: TextStyle (
                              fontSize: 14,
                            )),
                            style: ButtonStyle(
                              padding: MaterialStateProperty.all<EdgeInsets>(EdgeInsets.all(20.0)),
                              foregroundColor: MaterialStateProperty.all<Color>(Colors.white),
                              backgroundColor: MaterialStateProperty.all<Color>(Colors.pink),
                              shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                                RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(10.0),
                                    side: BorderSide(color: secondary)
                                ),
                              ),
                            ),

                          ),
                        )
                      ],


                    ),
                  )

              )
            ],
          ),
        )
    );
  }
}

预算列表拉取渲染页代码

import 'package:flutter/material.dart';
import 'package:monger_app/localization/localization_constants.dart';
import 'package:monger_app/page/transaction.dart';
import 'package:monger_app/theme/colors.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import './transaction.dart' as expense;
import './transaction.dart' as income;

class TransactionMonthly extends StatefulWidget {
  @override
  _TransactionMonthlyState createState() => _TransactionMonthlyState();
}

class _TransactionMonthlyState extends State<TransactionMonthly> with SingleTickerProviderStateMixin {

  TabController controller;
  @override
  void initState() {
    controller = new TabController(vsync: this, length: 2);
    super.initState();
  }
  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(getTranslated(context, 'budget_title'),),
        elevation: 0,
        brightness: Brightness.light,
        backgroundColor: primary,
        leading: IconButton(
          onPressed: (){
            Navigator.pop(context, MaterialPageRoute(builder: (context) => Transactions()));
          },
          icon: Icon(Icons.arrow_back_ios,
            size: 20,
            color: Colors.black,),
        ),
      ),
      body: StreamBuilder(
          stream: FirebaseFirestore.instance.collection('Budget').snapshots(),
          builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
            if (snapshot.hasData) {
              return ListView(
                children: snapshot.data.docs.map((document) {
                  return Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(children: [
                          SizedBox(width: 10,),
                          Text(document.get('name'),style: TextStyle(fontSize: 16,
                              color: primary,
                              fontWeight: FontWeight.w600
                          ),),
                        ],
                        ),
                        SizedBox(height: 10,),
                        Row(children: [
                          SizedBox(width: 10,),
                          Text(document.get('currency'),style: TextStyle(fontSize: 16,
                              color: primary,
                              fontWeight: FontWeight.w600
                          ),),
                          SizedBox(width: 10,),
                          Text(document.get('amount'),style: TextStyle(fontSize: 16,
                              color: primary,
                              fontWeight: FontWeight.w600
                          ),),
                        ],
                        ),
                        SizedBox(height: 8,),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            GestureDetector(
                              onTap: (){
                                Widget cancelButton = FlatButton(child: Text("Cancel"),
                                  onPressed: (){
                                    Navigator.pop(context);
                                  },
                                );
                                Widget deleteButton = FlatButton(child: Text("Delete"),
                                  onPressed: (){
                                    FirebaseFirestore.instance.collection('Budget').doc(document.id).delete();
                                    Navigator.pop(context);
                                  },
                                );
                                showDialog(
                                  context: context,
                                  builder: (context) => AlertDialog(
                                    title: Text('Delete Budget'),
                                    content: Text('Are you sure want to delete it?'),
                                    actions: [
                                      cancelButton,
                                      deleteButton,
                                    ],
                                  ),
                                );
                              },
                              child: Row(
                                children: [
                                  Icon(Icons.delete_forever_outlined,
                                    color: Colors.red,
                                  ),
                                  SizedBox(width: 6,),
                                  Text('Delete', style: TextStyle(fontSize: 16,
                                      color: Colors.red,
                                      fontWeight: FontWeight.w600
                                  ), ),
                                ],
                              ),
                            )
                          ],
                        )
                      ],)
                  );
                }).toList(),
              );
            }
            return Center(
              child: CircularProgressIndicator(),
            );
          }
      ),
    );
  }
}

实现方案

方案1:新增时直接合并数据(推荐,无冗余数据)

修改新增预算页保存按钮的逻辑,先查询是否存在同分类、同币种的预算,存在则累加金额更新,不存在再新增文档:

onPressed: () async {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final User user = _auth.currentUser;
  double inputAmount = double.parse(amount.text.trim());

  if(!_formKey.currentState.validate()){
    return;
  }
  _formKey.currentState.save();

  // 查询同分类同币种的已有预算
  QuerySnapshot existBudget = await collect
      .where('name', isEqualTo: widget.name)
      .where('currency', isEqualTo: selectCurrency)
      .get();

  if(existBudget.docs.isNotEmpty){
    // 存在则累加更新
    var doc = existBudget.docs.first;
    double oldAmount = double.parse(doc.get('amount'));
    double newAmount = oldAmount + inputAmount;
    await doc.reference.update({'amount': newAmount.toString()});
  }else{
    // 不存在则新增
    await collect.add({
      'name': widget.name,
      'currency': selectCurrency,
      'amount': inputAmount.toString(),
    });
  }
  amount.text = "";
  Navigator.pop(context);
},

方案2:前端拉取后聚合展示(适合需要保留每笔新增记录的场景)

修改预算列表页的渲染逻辑,先按「分类名+币种」分组累加金额,再渲染列表:

builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
  if (snapshot.hasData) {
    // 分组累加,key为 分类名_币种
    Map<String, Map<String, dynamic>> mergedMap = {};
    for (var doc in snapshot.data.docs) {
      String key = "${doc.get('name')}_${doc.get('currency')}";
      double currentAmt = double.parse(doc.get('amount'));
      if(mergedMap.containsKey(key)){
        mergedMap[key]['amount'] += currentAmt;
        mergedMap[key]['docIds'].add(doc.id);
      }else{
        mergedMap[key] = {
          'name': doc.get('name'),
          'currency': doc.get('currency'),
          'amount': currentAmt,
          'docIds': [doc.id]
        };
      }
    }
    // 渲染聚合后的列表
    List<Widget> listItems = mergedMap.values.map((item) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(children: [
              SizedBox(width: 10,),
              Text(item['name'],style: TextStyle(fontSize: 16,
                  color: primary,
                  fontWeight: FontWeight.w600
              ),),
            ],
            ),
            SizedBox(height: 10,),
            Row(children: [
              SizedBox(width: 10,),
              Text(item['currency'],style: TextStyle(fontSize: 16,
                  color: primary,
                  fontWeight: FontWeight.w600
              ),),
              SizedBox(width: 10,),
              Text(item['amount'].toStringAsFixed(0),style: TextStyle(fontSize: 16,
                  color: primary,
                  fontWeight: FontWeight.w600
              ),),
            ],
            ),
            SizedBox(height: 8,),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                GestureDetector(
                  onTap: (){
                    Widget cancelButton = TextButton(child: Text("取消"),
                      onPressed: (){
                        Navigator.pop(context);
                      },
                    );
                    Widget deleteButton = TextButton(child: Text("删除"),
                      onPressed: () async {
                        // 批量删除同组所有文档
                        for(var id in item['docIds']){
                          await FirebaseFirestore.instance.collection('Budget').doc(id).delete();
                        }
                        Navigator.pop(context);
                      },
                    );
                    showDialog(
                      context: context,
                      builder:
相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 23:54:00