这是我的数据的样子。我正在尝试将 Firestore 中的 map 字段对象转换为 flutter。
如果我的Firestore数据库中没有rating map,我可以很方便的使用下面的代码在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());
});
}
但是对于 Firestore 中的评分 map ,我不确定如何转换它。任何人都可以分享他们如何将 Firestore 中的 map 数据类型转换为 flutter 吗?提前致谢!
下面显示了模型的代码。
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
);
}
最佳答案
您可以创建评级模型并在评论模型中添加其参数。 看看下面的代码。
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,
);
}
关于firebase - 在 Flutter 中映射 Firestore 中的映射字段对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68012391/