首页 > 解决方案 > 将firestore子集合字段添加到列表中

问题描述

我正在尝试将子集合的字段添加到评论列表中。我可以知道我应该如何在 //To add to List// 部分中做到这一点吗?

“评论”集合包含 2 个子集合,即“1”和“2”。'1' 和 '2' 都包含 4 个字段的映射。

以下是firestore的代码和截图:

List<dynamic> reviewsList = [];
  Future _getReviews() async{
    firestore.collection('shops').doc(widget.shop.id).collection('reviews').get()
        .then((reviews){
          reviews.docs.forEach((result) {
            firestore.collection('shops').doc(widget.shop.id).collection('reviews').doc(result.id)
                .get().then((reviewDocumentSnapshot) {
               // To add to List //
            });
          });
    });
  }

Firestore 子集合

标签: fluttergoogle-cloud-firestore

解决方案


该问题与对异步的误解有关。将您的功能更改为

Future _getReviews() async{
      var reviews = await firestore.collection('shops').doc(widget.shop.id).collection('reviews').get();
   
      reviews.docs.forEach((result) {
        var reviewDocumentSnapshot= await firestore.collection('shops').doc(widget.shop.id).collection('reviews').doc(result.id);
         //add this snapshot to list.  
         reviewsList[your_object.fromJson(reviewDocumentSnapshot)]; 
      });
}

你的模型类将是

 class your_model {
  String name;
  String review;
  int star;
  String uid;

  your_model({this.name, this.review, this.star, this.uid});

  your_model.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    review = json['review'];
    star = json['star'];
    uid = json['uid'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name'] = this.name;
    data['review'] = this.review;
    data['star'] = this.star;
    data['uid'] = this.uid;
    return data;
  }
}

推荐阅读