0

I am trying to fetch a field name "total" from mongodb and add all the total for a particular user as shown below


  getCartTotal() async{

    var total = 0;
    Db db = new Db("mongodb://3.133.123.227/Kartofilldatabasetest");
    await db.open();
    var collection =  db.collection('cart');
    await collection.find({"customerId":phoneNumber}).forEach((v) {
      total = total + v["total"];

    });
    db.close();
    
    return total;

  }

I am trying to use the returned value of total as follow in the init function i am calling it everytime the page is opened.


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
   WidgetsBinding.instance.addPostFrameCallback((_) async {
      await getTotal();
    });
  }

  getTotal() async {

     totalCartValue = await Mongocart(phoneNumber: widget.phoneNumber,description: '',image: '',price: '',quantity: '',total: '').getCartTotal();




  }


  @override
  Widget build(BuildContext context) {

    print(totalCartValue);
    return Container();
  }
}

Whenever i am trying to print the value it shows instance of future and not the value is printed. This is what is getting printed Instance of 'Future'

Below is my database screenshot

enter image description here

I want fetch the field total of all the object and assign it in the totalcartvalue currently it is printing 0.

CodeTasy
  • 119
  • 9
  • Does this answer your question? [What is a Future and how do I use it?](https://stackoverflow.com/questions/63017280/what-is-a-future-and-how-do-i-use-it) – nvoigt Sep 28 '20 at 06:41
  • Make the variable explicitly the type you want it to be and then follow the guide [here](https://stackoverflow.com/questions/63017280/what-is-a-future-and-how-do-i-use-it). – nvoigt Sep 28 '20 at 06:42
  • I have edited my question .. Could you please check – CodeTasy Sep 28 '20 at 07:16
  • To be honest, that seems to be an incredibly "hacky" thing to do. Please read the link I posted, it contains a tutorial how to properly work with futures. – nvoigt Sep 28 '20 at 07:32

1 Answers1

0

Since you are using async in the getTotal() function, the result should be using await, otherwise it would just build concurrently with the data is being retrieve, thus no data is displayed on build.

@override
void initState() {
    // TODO: implement initState
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) async {
        await getTotal();
    });
}
Adlan Arif Zakaria
  • 1,706
  • 1
  • 8
  • 13