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..
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
You can do fetchSocial async and await the result to return:
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() or 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.
To get a field, or the Map<String, dynamic>
of all fields, you need the data from a single document. For example, to get the message
field fro the first document from the collection, you can do:
return SocialShare.fromJson(value.docs[0].data());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.