[英]Flutter firebase get a field from document
I'm trying to get the message from a field in a collection.我正在尝试从集合中的字段获取消息。 It is a read only data, i have modeled it like this这是一个只读数据,我已经像这样建模了
class SocialShare {
final String message;
SocialShare({
this.message,
});
factory SocialShare.fromJson(Map<String, dynamic> json) {
return SocialShare(
message: json['message'],
);
}
}
I have a collection named 'Social Share and contains a doc with a single field called message..我有一个名为“社交分享”的集合,其中包含一个文档,其中包含一个名为 message 的字段。
Here is how i call it我是这样称呼它的
class SocialShares {
final CollectionReference _socialMessage =
FirebaseFirestore.instance.collection('socialShare');
Future<SocialShare> fetchsocial() {
return _socialMessage.get().then((value) {
return SocialShare.fromJson(value); // how can i call it
});
}
}
How can i get a that value from firebase我如何从 firebase 获得该值
You can do fetchSocial async and await the result to return:您可以执行 fetchSocial async 并等待结果返回:
fetchSocial() async{
var value = await _socialMessage.get();
return SocialShare.fromJson(value);
}
then you have to call fetchSocial method with await or then where you need it.然后你必须用 await 或者你需要的地方调用 fetchSocial 方法。
await fetchSocial() or fetchSocial.then...等待 fetchSocial() 或 fetchSocial.then...
The value
in _socialMessage.get().then((value) {
is a QuerySnapshot
object , which contains the DocumentSnapshot
s of all documents in the socialShare
collection. value
_socialMessage.get().then((value) {
中的值是一个QuerySnapshot
object ,其中包含socialShare
集合中所有文档的DocumentSnapshot
。
To get a field, or the Map<String, dynamic>
of all fields, you need the data from a single document.要获取一个字段或所有字段的Map<String, dynamic>
,您需要来自单个文档的数据。 For example, to get the message
field fro the first document from the collection, you can do:例如,要从集合中的第一个文档中获取message
字段,您可以执行以下操作:
return SocialShare.fromJson(value.docs[0].data());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.