0xLasadie
0xLasadie

Reputation: 307

Adding firestore subcollection fields into List

i am trying to add the fields of a subcollection into reviewsList. May i know how should I do that in the //To add to List// part?

The 'Reviews' collection contains 2 subcollections namely '1' and '2'. Both '1' and '2' each contain a map of 4 fields.

Below are the codes and screenshot of 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 subcollection

Upvotes: 0

Views: 180

Answers (1)

Faiizii Awan
Faiizii Awan

Reputation: 1710

the issue is related to misunderstanding of async. change your function as

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

and your model class will be

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

Upvotes: 1

Related Questions