skip to Main Content

My app has a feature where users can add their reviews. For example, it’s like leaving a comment on Facebook. posting a user review should be stored in the reviews list. I think it can’t be done this way .doc(DocId).update(review.toJson()).

This is a screenshot of the data structure of my Firebase Firestore.
enter image description here

I tried to solve this firestore.FieldValue if I do that, an error message will come like this: I/flutter (21250): type '_Map<String, String?>' is not a subtype of type 'List<dynamic>'

this is my Firestore query.

Future<void> addReview (placeId,Review review) async{

    try{

      await FirebaseFirestore.instance.collection('attractions')
      .where('placeId',isEqualTo: placeId).get()
      .then((querySnapshot) {
        for (var ele in querySnapshot.docs) {

            FirebaseFirestore.instance
            .collection('attractions')
            .doc(ele.id)
            .update({
              'reviews': FieldValue.arrayUnion(review.toJson())});
          
        }

      });

    }catch(e){
      print(e);
    }
    
  }



}

this is my review.dart model class :

class Review {

  final String reviewId;
  final String? name;
  final String publishAt;
  final String? reviewerPhotoUrl;
  final String text;

  Review({
    required this.reviewId,
    required this.name,
    required this.publishAt,
    required this.reviewerPhotoUrl,
    required this.text,
  });

  toJson ()=>{
    "reviewId":reviewId,
    "name":name,
    "publishAt":publishAt,
    "reviewerPhotoUrl":reviewerPhotoUrl,
    "text":text
  };

  

}

I think there is a way around this or there is an alternative to doing this.

2

Answers


  1. Try Using :

     FirebaseFirestore.instance
                .collection('attractions')
                .doc(ele.id)
                .update({
                  'reviews': [review.toJson()]});
    

    I think your review type on firestore is List still it is not working provide proper typing

    Login or Signup to reply.
  2. When you iterate through querySnapshot.docs the ele object is of type QueryDocumentSnapshot. So there is no need to create a reference you can simply call reference. Besides that, the review is an object of type Review, so as far as I know there is no need to map the object to JSON, you can directly pass the object. So in code, it will be as simple as:

    //    👇
    ele.reference.update({
        'reviews': FieldValue.arrayUnion(review)
    }); //                                👆
    

    If you want to add the object as a Map, then you should define it as:

    Map<String, dynamic> review = {
      'reviewId': reviewId,
      'name': name,
      'publishAt': publishAt,
      'reviewerPhotoUrl': reviewerPhotoUrl,
      'text': text
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search