如何对从firebase检索的值执行计算



这是我的应用程序屏幕截图,我正在使用流生成器从firebase检索数据

在此处输入图像描述

现在我想把";现金收入";以及";套现";并在上述卡片中显示它们的总和";手头现金";以及";今天的余额"分别地

我需要创建另一个流生成器还是其他什么?

这是我的代码:

class CaShBookRegister extends StatefulWidget {
const CaShBookRegister({Key? key}) : super(key: key);
@override
_CaShBookRegisterState createState() => _CaShBookRegisterState();
}
class _CaShBookRegisterState extends State<CaShBookRegister> {
final _firestore = FirebaseFirestore.instance;
DateTime date = DateTime.now();
late var formattedDate = DateFormat('d-MMM-yy').format(date);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.symmetric(vertical: 18.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
const SizedBox(
height: 16.0,
),
Padding(
padding: const EdgeInsets.all(14.0),
child: Row(
children: [
Expanded(
child: ReuseableCard(
textcolour: Colors.white,
buttonColour: Colors.green,
text: "Cash in hand",
),
),
const SizedBox(
width: 8.0,
),
Expanded(
child: ReuseableCard(
buttonColour: Colors.red,
textcolour: Colors.white,
text: "Today's balance",
),
),
],
),
),
StreamBuilder(
stream: _firestore.collection('CASHINCASHOUT').snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return const Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const Text("Loading");
}
if (snapshot.hasData) {
List<DataCell> displayedDataCell = [];
for (var item in snapshot.data!.docs) {
displayedDataCell.add(
DataCell(
Text(
item['DATE'].toString(),
),
),
);
displayedDataCell.add(
DataCell(
Text(
item['CASHIN'].toString(),
style: const TextStyle(color: Colors.green),
),
),
);
displayedDataCell.add(
DataCell(
Text(
item['CASHOUT'].toString(),
style: const TextStyle(color: Colors.red),
),
),
);
}
return FittedBox(
child: DataTable(
columns: const <DataColumn>[
DataColumn(
label: Text(
'Date',
),
),
DataColumn(
label: Text(
'Cash In',
),
),
DataColumn(
label: Text(
'Cash Out',
),
),
],
rows: <DataRow>[
for (int i = 0; i < displayedDataCell.length; i += 3)
DataRow(cells: [
displayedDataCell[i],
displayedDataCell[i + 1],
displayedDataCell[i + 2]
]),
],
),
);
}
return const CircularProgressIndicator();
},
),
const Spacer(),
Padding(
padding: const EdgeInsets.all(14.0),
child: Row(
children: [
Expanded(
child: ReusableButton(
color: Colors.red,
text: "Add Enteries",
onpress: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const CashInCashOut(),
),
);
},
)),
],
),
),
],
),
),
);
}
}

实现这一点的一种方法是从内部的firestore订阅流initState,其中可以计算";手头现金";以及";今天的余额"并用CCD_ 2替换为变量。

然后您将这些变量传递到您的小部件中,每当该变量更新时,小部件就会重新构建自己的

int _cashInHand = 0;
int _balance = 0;
@override
void initState() {
_firestore.collection('CASHINCASHOUT').snapshots().listen((qs) {
setState(() {
_cashInHand = <calculate cash in hand from snapshots>
_balance = <calculate today's balance from snapshots>
});
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
....
Padding(
padding: const EdgeInsets.all(14.0),
child: Row(
children: [
Expanded(
child: ReuseableCard(
textcolour: Colors.white,
buttonColour: Colors.green,
text: _cashInHand.toString(), // <- pass the variable
),
),
const SizedBox(
width: 8.0,
),
Expanded(
child: ReuseableCard(
buttonColour: Colors.red,
textcolour: Colors.white,
text: _balance.toString(), // <- pass the variable
),
),
],
),
),

您可能来自一个坚实的SQL背景,因为我确实有,而且有一个巨大的难以理解的差异,从SQL到firebase,所以您必须以不同的方式思考。

我的建议是,我观看了Firestore YouTube上的所有视频(香奈儿官方视频(,并与之保持一致,而且我确实阅读了很多官方文件,我可以选择:

A。当存储一个新事务时(我假设您存储了每个cacheIn/Out文档(,您确实计算了该日期的新余额,这样您就可以将余额存储为一个固定值,并根据需要请求结果。我认为这对你来说是最好的选择,要做到这一点,你可以做一笔交易来保持良好的状态:

// Run transaction to do all changes at once
FirebaseFirestore.instance
.runTransaction((transaction) async {
// Store you "transaction"
await FirebaseFirestore
.instance
.collection("TRANSACTIONCOLLECTION")
.add(transaction.toJson());
// With your transaction, update your CACHEINCACHEOUT report collection
transaction.update(
// Your CASHINCASHOUT doc reference
await FirebaseFirestore
.instance
.collection('CASHINCASHOUT')
.doc('itemId'),
/// You can use increment do update the value for cache in or cache out,
/// see this example as i increase in transaction.cacheIn
{
'CACHEIN': FieldValue.increment(transaction.cacheIn)
}
)
});

您可以在<(FlutterFire文档([https://firebase.flutter.dev/docs/firestore/usage#transactions]>

此外,我在(Firebase YouTube(上观看了整个播放列表至少3次,以平息我愤怒的SQL思维15年[https://www.youtube.com/watch?v=v_hR4K4auoQ&list=PLl-K7zZEsYLuG5MCVEzXAQ7ACzBCuZgZ]