0

I want to fetch a simple document from firebase and store it in a map as soon as the screen loads, I'm trying to do this through the init state, i.e. calling the fetching function in the init state, but my map is still null. Here is some code :

Map<String, int> minDelivery;

  void minimumDelivery() async{
    await FirebaseFirestore.instance
        .collection("minimumDelivery")
        .limit(1)
        .get()
        .then((QuerySnapshot qs) {
      qs.docs.forEach((doc) {
        int amount = doc["min_amount"];
        int charge = doc["charge"];
        minDelivery = {
          "amount":amount,
          "charge":charge
        };
      });
    });
  }

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

But the map is null when I am trying to access its data. I don't see where the problem is.I just want the map to have the required data at the start of screen.

  • Check this out, your map is in a future and needs time to be filled. This is why its null after initState. Use a FutureBuilder https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html – Ozan Taskiran Aug 30 '22 at 15:40
  • Can i not have any simple solution as my build method is quite complex and wrapping it in future builder would be tough. Also, can you help me implement a future builder in this code? – Necromancer Aug 30 '22 at 17:15
  • It isn't complex :) Many IDE's can wrap a widget over other widgets with a simple command (https://i.gyazo.com/affa28c5c30017354d8f7a2d41d46942.png check this out). In this case you would select Builder and change it to a FutureBuilder – Ozan Taskiran Aug 30 '22 at 17:19
  • Upload your FutureBuilder Code. My guess is you dont ask if the snapshot has data, like this: if (snapshot.hasData) { // return here your ui code } else return Container(); – Ozan Taskiran Aug 30 '22 at 17:48
  • Check the link in the first comment and scroll down for an example :) – Ozan Taskiran Aug 30 '22 at 17:49

0 Answers0