Home > Back-end >  How To get The Total of values in Flutter firestore? elevated button text
How To get The Total of values in Flutter firestore? elevated button text

Time:09-27

so below iam able to get the total sum of my prices from firestore but i cant seem to be able to call it to text in elevated button here is my code the total sum comes to me correct as i said but the thing is calling the final value to my button any help will be appreciated





class cartpage extends StatefulWidget {
  const cartpage({Key? key}) : super(key: key);

  @override
  State<cartpage> createState() => _cartpageState();
}

class _cartpageState extends State<cartpage> {

  AuthService get _auth => AuthService();
  final Stream<QuerySnapshot> Cart = FirebaseFirestore.instance
      .collection('Cart')
      .doc(FirebaseAuth.instance.currentUser!.uid)
      .collection("UserCart")
      .doc('test')
      .collection('final')
      .snapshots();
  var total = FirebaseFirestore.instance
      .collection('Cart')
      .doc(FirebaseAuth.instance.currentUser!.uid)
      .collection("UserCart")
      .doc('test')
      .collection('final')
      .get()
      .then((querySnapshot) {
    num sum = 0.0;
    querySnapshot.docs.forEach((element) {
      num value = element.data()["Price"];
      sum = sum   value;
    });
   
    return sum;
  });

  @override
  Widget build(BuildContext context) {
    return  // i removed some of the code from here //
            ElevatedButton(
              onPressed: null,
              child: Text('$sum'),
            )
          ],
        )
      ],
    );
  }
}

CodePudding user response:

Your Firebase request returns you some data correctly, but you should remember that it takes some time. In your example you are trying to use sum variable, but this variable does not receive the data form Firebase. You should first display some Loading (e.q.: CircularProgressIndicator widget) and call a Firebase request. When you receive the response, then you can change the state and pass sum to your widget. So create asynchronous method and move your Firebase request call there with await keyword. PS. So you use some state management? e.g: BLoC?

  • Related