Flutter Firebase-从文档获取特定字段

时间:2020-06-02 01:27:27

标签: android ios firebase flutter google-cloud-firestore

我正在尝试从Firebase集合中的文档中获取一个名为“ specie”的特定字段。我正在尝试如下,但我有类型'Future'的错误不是'String'类型的子类型。我在做什么错了?

存储库方法:

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

实体方法:

 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);
}

2 个答案:

答案 0 :(得分:2)

我找到了解决方案。不需要fromJson()方法,我只更改了存储库方法:

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;
  }

答案 1 :(得分:1)

尝试一下。

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

这就是我学会从Firestore获取文档的方法 https://medium.com/@yasassandeepa007/how-to-get-sub-collection-data-from-firebase-with-flutter-fe1bda8456ca