Flutter Firestore 使用异步检索所有文档内容
Flutter Firestore retrieve all document contents using async
使用 print(await _getAllMessages()); 调用时未返回消息;
我正在尝试从指定集合中的每个文档中检索数据。我想将此文档转换为单个字符串并将其打印到控制台。
_getAllMessages() 异步{
// 打印(数据["message"]));
String messages = "Copy of message body below: \n";
Firestore.instance
.collection('rooms')
.document('roomA')
.collection('messages')
.snapshots()
.listen((data) => data.documents.forEach(
(doc) => messages += doc.data.toString(),
));
return messages;
}
有两个问题,首先你应该使用 .getDocuments
函数而不是 .listen
,其次 return 应该在 .getDocuments
函数中(或者使用异步等待)。
_getAllMessages() async {
String messages = "Copy of message body below: \n";
Firestore.instance
.collection('rooms')
.document('roomA')
.collection('messages')
.getDocuments((data) => data.documents.forEach(
(doc) => messages += doc.data.toString(), );
return messages;
);
}
使用 print(await _getAllMessages()); 调用时未返回消息;
我正在尝试从指定集合中的每个文档中检索数据。我想将此文档转换为单个字符串并将其打印到控制台。
_getAllMessages() 异步{ // 打印(数据["message"]));
String messages = "Copy of message body below: \n";
Firestore.instance
.collection('rooms')
.document('roomA')
.collection('messages')
.snapshots()
.listen((data) => data.documents.forEach(
(doc) => messages += doc.data.toString(),
));
return messages;
}
有两个问题,首先你应该使用 .getDocuments
函数而不是 .listen
,其次 return 应该在 .getDocuments
函数中(或者使用异步等待)。
_getAllMessages() async {
String messages = "Copy of message body below: \n";
Firestore.instance
.collection('rooms')
.document('roomA')
.collection('messages')
.getDocuments((data) => data.documents.forEach(
(doc) => messages += doc.data.toString(), );
return messages;
);
}