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.
CodePudding user response:
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
CodePudding user response:
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
CodePudding user response:
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);