我正在尝试从集合中的字段获取消息。这是一个只读数据,我将其建模如下
class SocialShare {
final String message;
SocialShare({
this.message,
});
factory SocialShare.fromJson(Map<String, dynamic> json) {
return SocialShare(
message: json['message'],
);
}
}我有一个名为'Social Share‘的集合,其中包含一个文档,该文档具有一个名为message的字段。
我是这样称呼它的
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
});
}
}如何从firebase获取该值
发布于 2021-04-15 21:15:23
您可以执行fetchSocial异步操作,并等待结果返回:
fetchSocial() async{
var value = await _socialMessage.get();
return SocialShare.fromJson(value);
}然后你必须调用带有等待的fetchSocial方法,或者在你需要的地方调用它。
等待fetchSocial()或fetchSocial.then ...
发布于 2021-04-15 21:34:42
_socialMessage.get().then((value) {中的value是一个QuerySnapshot object,它包含socialShare集合中所有文档的DocumentSnapshot。
要获取一个字段或所有字段的Map<String, dynamic>,您需要来自单个文档的数据。例如,要获取集合中第一个文档的message字段,可以执行以下操作:
return SocialShare.fromJson(value.docs[0].data());https://stackoverflow.com/questions/67109057
复制相似问题