简体   繁体   中英

Flutter Firebase - Get a specific field from document

I'm trying to get a specific field called "specie" from a document in a Firebase collection. I am trying as follows but I have an error of type 'Future ' is not a subtype of type 'String' . What am I doing wrong?

Repository method:

getSpecie(String petId) {
    Future<DocumentSnapshot> snapshot = petCollection.document(petId).get();
    return snapshot.then((value) => Pet.fromSnapshot(value).specie);
  }

Entity method:

 factory Pet.fromSnapshot(DocumentSnapshot snapshot) {
    Pet newPet = Pet.fromJson(snapshot.data);
    newPet.reference = snapshot.reference;
    return newPet;
  }

 factory Pet.fromJson(Map<String, dynamic> json) => _PetFromJson(json);

Pet _PetFromJson(Map<String, dynamic> json) {
  return Pet(json['name'] as String,
      specie: json['specie'] as String);
}

I found a solution. No needed fromJson() method, I only changed the repository method:

Future<String> getSpecie(String petId) async {
    DocumentReference documentReference = petCollection.document(petId);
    String specie;
    await documentReference.get().then((snapshot) {
      specie = snapshot.data['specie'].toString();
    });
    return specie;
  }

Try this..

getSpecie(String petId) async{
    Future<DocumentSnapshot> snapshot = await petCollection.document(petId).get();
    return snapshot.then((value) => Pet.fromSnapshot(value).specie);
  }

This is how I learned to get documents from firestore https://medium.com/@yasassandeepa007/how-to-get-sub-collection-data-from-firebase-with-flutter-fe1bda8456ca

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM