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.
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
Try Using :
I think your review type on firestore is List still it is not working provide proper typing
When you iterate through
querySnapshot.docs
theele
object is of type QueryDocumentSnapshot. So there is no need to create a reference you can simply call reference. Besides that, thereview
is an object of typeReview
, 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:If you want to add the object as a
Map
, then you should define it as: