Flutter firebase get a field from document

268

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 ...

Share:
268
Febin Johnson
Author by

Febin Johnson

Updated on December 29, 2022

Comments

  • Febin Johnson
    Febin Johnson over 1 year

    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

  • Febin Johnson
    Febin Johnson about 3 years
    I'm using to load this message to a share button. And how can i avoid the error 'QuerySnapshot' can't be assigned to the parameter type 'Map<String, dynamic>
  • Jorge Vieira
    Jorge Vieira about 3 years
    you are getting all documents on the collection, so you need to call some like SocialShare.fromJson(value.docs[0].data), but this way you will aways get the first document. guess you should pass the id of the document to get only it from the collection. like this FirebaseFirestore.instance.collection('socialShare').doc(ido‌​fthedocument)
  • Febin Johnson
    Febin Johnson about 3 years
    can't i simply pass like this onPressed: () { Share.share(socialshares.fetchSocial()); },
  • Jorge Vieira
    Jorge Vieira about 3 years
    @FebinJohnson i think will not works like this cause are async calls to the server, so you need to make the call, wait the result and then pass to the share, i'm not sure but i think will not work directly.