我使用ListView.builder构造函数通过从Firestore检索数据来构建列表。
我有两个集合,在这些集合下我有不同文档中的数据。
收集消息:
消息中的每个文档都有以下键:msgBody,sender。我将发件人ID存储在邮件文档中的sender字段中,这实际上是收集Users中相应用户的文档名称。
收藏用户:
我目前正在使用以下代码来阅读邮件集合并获取其中的文档,然后我在sender字段中获取值并创建对相应发件人文档的文档引用,并尝试使用Users文档获取发件人详细信息并使用我列表中的数据。
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
],
);
}
}
)
如何从不同集合下的不同文档中读取数据并在同一ListView.builder中使用它?
任何帮助将非常感谢:)
在获取用户名时,已经构建了UI。您需要为每个文档都有一个嵌套的FutureBuilder
或StreamBuilder
。或者在单独的方法中调用async
,在initState
中调用此方法并填充相应的字段,然后将它们加载到build
方法中的UI中。