I am using the ListView.builder constructor to build a list by retrieving data from Firestore.
I have two collections under which I have data in separate documents.
Collection Messages:
Every document in message has the following keys: msgBody, sender. I store the sender id in the sender field in the message documents, which is actually the document name of the respective user in collection Users.
Collection Users:
I am currently using the follwing code to read the messages collection and get the documents in it, then I get the value in sender field and create a document reference to the respective sender document and try to get the sender details using the Users document and use the data from the it in my list.
child: StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('Messages').snapshots(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) return Center(child: CircularProgressIndicator());
return new ListView.builder(
itemCount: snapshot.data.documents.length,
padding: const EdgeInsets.all(6.0),
itemBuilder: (context, index) {
DocumentSnapshot ds = snapshot.data.documents[index];
DocumentReference tRef = Firestore.instance.document('/users/'+ds['sender']);
DocumentSnapshot tRefD;
tRef.get().then((tData){
print(tData.data); // I can see the sender data in the console here
tRefD = tData;
});
if (ds.data.isNotEmpty)
{
return Column(
children: <Widget>[
Text(ds['sender']),
Text(tRefD['name']), //App crashes here works when I comment this line
],
);
}
}
)
How do I read data from different documents under different collections and use it in the same ListView.builder?
Any help will be really appreciated :)
By the time your user name is fetched, the UI had already been built. You either need to have a nested FutureBuilder or StreamBuilder one for each document. Or make your async calls in a separate method, call this method in your initState and populate the respective fields and then load them into the UI inside your build method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With