Home > Blockchain >  FutureBuilder can't "see" data / snapshot.hasData
FutureBuilder can't "see" data / snapshot.hasData

Time:10-25

I have a Future function to get data from Firebase, that is not empty queries correctly:

Future  getProducts(vendorId) async {
  await vendorsInfoColl.doc(vendorId)
    .collection("products")
    .get()
    .then((QuerySnapshot querySnapShot) async {
      if (querySnapShot.docs.isNotEmpty){
        print('not empty');
        print(querySnapShot.docs);
        return querySnapShot.docs;
      } else {
        print('snapshot empty');
        return null;
      }
    });
}

I just have trouble getting a FutureBuilder see it. Keeps saying there is empty data.

Widget build(BuildContext context) {
  return AlertDialog(
    // pull title from db
    // title: Future Text(vendorTitle.toString()),
    title: Text(vendorTitle.toString()),
    content: FutureBuilder(
      future: VendorDatabase().getProducts(widget.vendorId),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        print(snapshot.connectionState);
        if (snapshot.connectionState == ConnectionState.waiting) {
          return CircularProgressIndicator();
        } else if (snapshot.connectionState == ConnectionState.done) {
          if (snapshot.hasError) {
            return const Text('Error');
          } else if (snapshot.hasData) {
            var blabla = snapshot.data;
            print('there is snapshot data:  $blabla');
            return ListView.builder(
              itemCount: 3,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text(blabla['products']) //<-- i know this is wrong but can't fixt it till future builder actually sees some data.
                );
              }
            );
          } else {
            return const Text('Empty data');
          }
        } else {
          return Text('State: ${snapshot.connectionState}');
        }
      }
    )
  );
}

It would be great if can also get some tips on how to put it in a list :)

CodePudding user response:

You're not returning anything inside getProducts:

Future getProducts(vendorId) async {
  return await vendorsInfoColl.doc(vendorId)
      .collection("products")
      .get()
      .then((QuerySnapshot querySnapShot) async {
    if (querySnapShot.docs.isNotEmpty){
      return querySnapShot.docs;
    } else {
      return null;
    }
  });
}

To avoid this in the future, declare a type in your Future:

//    vvvvvvvvvvvvvvvv
Future<List<Document>> getProducts(vendorId) async {
  • Related