【问题标题】:Flutter Firebase - Get a specific field from documentFlutter Firebase - 从文档中获取特定字段
【发布时间】:2020-09-20 09:55:58
【问题描述】:

我正在尝试从 Firebase 集合中的文档中获取名为“specie”的特定字段。我正在尝试如下,但我有一个错误 type 'Future' is not a subtype of type '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);
}

【问题讨论】:

  • 可能您在getSpecie 方法中缺少await 字段。
  • 嗨,我将 getSpecie 更改为 async 并在返回时添加了 await 但仍然是同样的问题

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    试试这个..

    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

    【讨论】:

    • 感谢您的回答,但问题仍然存在并且仍然相同
    猜你喜欢
    • 2021-07-04
    • 2021-07-10
    • 2021-02-01
    • 2020-11-05
    • 2021-07-20
    • 2022-10-15
    • 2019-02-26
    • 2018-09-04
    • 2021-07-22
    相关资源
    最近更新 更多