Search code examples
flutterlistviewgoogle-cloud-firestoreflutter-futurebuilder

Wait a function to be done in ListView


I need to wait my function to be done in a ListView because of a Firestore request. I tried using Future.wait() but it does not work.

FutureBuilder<QuerySnapshot>(
                    future: FirebaseFirestore.instance
                        .collection('Statements')
                        .where('userID',isEqualTo: context.watch<User>().uid)
                        .get(),
                    builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
                      if (snapshot.hasError) {return Text("Erreur");}
                      if (snapshot.connectionState == ConnectionState.waiting) {
                        return Text("Loading");}
                      return Expanded(
                        child:ListView.builder(
                          itemCount: snapshot.data.docs.length,
                            itemBuilder: (context, index) {
                              DocumentSnapshot document = snapshot.data.docs[index];
                              Future.wait([getStatementData(document)]);
                              return StatementCard(statement:selectedStatement,
                                           accommodation : relatedAccommodation,
                                           owner : relatedOwner);
                            },
                        )

Here is the function called :

Future getStatementData(document)  async {

    selectedStatement = Statement.fromFirebase(document);

    document.data()["accommodation"].get().then((value) {
      relatedAccommodation = Accommodation.fromFirebase(value);});

     await FirebaseFirestore.instance
         .collection('Owners')
         .doc(document["ownerList"][0])
         .get().then((value) {
           print(value.data());
           relatedOwner = Owner.fromFirebase(value);
     });

  }

Should I use another future builder ?


Solution

  • You should do it like this by returning another Future Builder inside :

       ListView.builder(
              itemCount: snapshot.data.docs.length,
              itemBuilder: (context, index) {
             DocumentSnapshot document = snapshot.data.docs[index];
            return  FutureBuilder(
          future: getStatementData(document) ,
          builder: (context, snapshot) {
            return snapshot.connectionState == ConnectionState.done
                   ? StatementCard(statement:selectedStatement,
                    accommodation : relatedAccommodation,
                     owner : relatedOwner);
                   : Container(); 
        );
          },
             )