繁体   English   中英

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

[英]Flutter Firebase - Get a specific field from document

我试图从 Firebase 集合中的文档中获取一个名为“specie”的特定字段。 我正在尝试如下,但我有一个类型为 '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);
}

我找到了解决方案。 不需要 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;
  }

尝试这个..

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获取文档的方法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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