Reputation: 646
This is how my data look like. I'm trying to convert a map field object in Firestore to flutter.
If there isn't a rating map in my Firestore database, I can easily use the following code to convert the data in Flutter
firestore.collection('test').doc('I1raMaJArb1sWXWqQErE')
.snapshots().listen((snapshot) {
if (snapshot.docs != null) {
var map = snapshot.docs;
if (map != null) {
map.forEach((change) {
Review review = Review.fromJson(change.data());
});
}
But with the rating map in Firestore, I'm not sure how to convert it. Can anyone share how they would convert a map datatype in Firestore to flutter? Thanks in advance!
Below shows the code for the model.
class Reviews {
String UserID;
String UserName;
//what do I put for the rating
Review({
this.UserID,
this.UserName
//what do I put for the rating
});
factory ChatChannel.fromJson(Map<dynamic, dynamic> json) => ChatChannel(
UserID: json['UserID'],
UserName: json['UserName'],
//what do I put for the rating
);
Map<String, dynamic> toJson() => {
"UserID": UserID,
"UserName": UserName,
//what do I put for the rating
);
}
Upvotes: 5
Views: 4440
Reputation: 916
You can create a model for ratings and add its parameter in Review Model. Have a look in below code.
class Reviews {
String UserID;
String UserName;
Ratings ratings;
Review({
this.UserID,
this.UserName
//what do I put for the rating
});
factory ChatChannel.fromJson(Map<dynamic, dynamic> json) => ChatChannel(
UserID: json['UserID'],
UserName: json['UserName'],
Ratings: Ratings.fromJson(json['ratings'])
);
Map<String, dynamic> toJson() => {
"UserID": UserID,
"UserName": UserName,
"ratings": ratings.toJson(),
);
}
class Ratings{
String oneStar;
String twoStar;
String threeStar;
Ratings({this.oneStar, this.twoStar,this.threeStar});
factory Ratings.fromJson(Map<dynamic, dynamic> json) => Ratings(
oneStar: json['1-star'],
twoStar: json['2-star'],
threeStar: json['3-star'],
);
Map<String, dynamic> toJson() => {
"1-star": oneStar,
"2-star": twoStar,
"3-star": threeStar,
);
}
Upvotes: 4
Reputation: 716
You can maintain the ratings field as a Map<String, int>
type in the Reviews
class like how you hold other fields.
class Reviews {
Reviews({
this.userID,
this.userName,
this.ratings,
});
String userID;
String userName;
Map<String, int> ratings;
factory ChatChannel.fromJson(Map<dynamic, dynamic> json) => ChatChannel(
userID: json['userID'],
userName: json['userName'],
ratings: json['ratings']);
Map<String, dynamic> toJson() =>
{"userID": userID, "userName": userName, 'ratings': ratings};
}
Upvotes: 1