Flutter Firebase - Get a specific field from document
5,642
Solution 1
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;
}
Solution 2
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
![Naruto The Kid Uzumaki](https://i.stack.imgur.com/AHUYa.png?s=256&g=1)
Author by
Naruto The Kid Uzumaki
Updated on December 21, 2022Comments
-
Naruto The Kid Uzumaki over 1 year
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); }
-
Naruto The Kid Uzumaki about 4 yearsThanks for your answer but the problem persist and still the same