FilipeOS
FilipeOS

Reputation: 859

Flutter load ListView item async

How can a ListView item refresh after each async task?

I have 2 collections on firebase that needs to be accessed and please, if there's another way please advise since I'm new in Firebase and Flutter.

My users have a collection inside called favorites with the userID field (same of the document id) and I load the ListView with all the users data BUT only with the ones that match that IDs (to avoid loading for example 1000 users for no reason = $$$).

According my code and my tests on the Run window I get the value of each user but my ListView on the app shows blank. I tried to place a setstate but the app refreshs non-stop.

I tried to create a separated function but simply I can't get it returning the list of document snapshots.

Thank you

FutureBuilder(
              future: Firestore.instance.collection('users').document(id).collection('favorites').getDocuments(),
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  List<DocumentSnapshot> userDocs = [];
                  snapshot.data.documents.forEach((doc) async {
                    await Firestore.instance.collection('users').document(doc.documentID).get().then((user) {
                      userDocs.add(user);
                    });
                  });
                  return ListView(
                    children: userDocs.map((document) {
                      return buildItem(context, document);
                    }).toList(),
                  );
                }
              },
            ),

Upvotes: 0

Views: 1815

Answers (1)

FilipeOS
FilipeOS

Reputation: 859

So, after weeks on this without any help I finally done it.

  1. StreamBuilder is getting only the documents on favorites:

    stream: Firestore.instance.collection('u').document(id).collection('f').snapshots()

  2. ListView.Builder is returning a new Widget (MessageTile Stateful widget)

    return MessageTile(ctx: context, doc: snapshot.data.documents[index]);

  3. Inside the Statefull widget I'm returning a FutureBuilder<DocumentSnapshot> that is fetching ONLY the user matching the userId:

    future: Firestore.instance.collection('u').document(doc['userId']).get()

Simple right? ..

Upvotes: 1

Related Questions