'Getting sum of amounts from firestore
class totalDS extends StatefulWidget {
const totalDS({
Key? key,
}) : super(key: key);
@override
_totalDSState createState() => _totalDSState();
}
double _total = 0.00;
class _totalDSState extends State<totalDS> {
Future getTotal() async {
final _firestore = FirebaseFirestore.instance.collection('DailySale').get();
_firestore.then((querySnapshot) => {
querySnapshot.docs.forEach((element) {
for (var i = 1; i < element.data().length; i++) {
_total = _total + element.data()['invAmountDS'];
}
})
});
}
@override
Widget build(BuildContext context) {
return Container(child: Text('$_total'.toString()));
}
}
I m getting the sum as 0.0
anybody can help me regarding this? i want to display total sum of the invoices.
Solution 1:[1]
void main() {
final myList = [1, 3, 5, 8, 7, 2, 11];
final result = myList.fold(0, (sum, element) => sum + element);
print(result);
}
Use Fold Method
Solution 2:[2]
In code you provided, you never even call getTotal() function. You can call it in initState() method like this:
@override
void initState() {
super.initState();
getTotal();
}
And you should also add setState() function after you finish your for loop
for (var i = 1; i < element.data().length; i++) {
_total = _total + element.data()['invAmountDS'];
}
setState((){});
This will make the widget to rebuild when the function counted _total value
Solution 3:[3]
This is best method to add ,
var sum = [1, 2, 3].reduce((a, b) => a + b);
but if the list is empty than to handle this empty condition we prefer fold() over .reduce()
int sum = [1, 2, 3].fold(0, (a, b) => a + b);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tasnuva Tavasum oshin |
| Solution 2 | Eimantas G |
| Solution 3 |
