firebase - 在 Flutter 中映射 Firestore 中的映射字段对象

标签 firebase flutter dart google-cloud-firestore

这是我的数据的样子。我正在尝试将 Firestore 中的 map 字段对象转换为 flutter。

enter image description here

如果我的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/

相关文章:

swift - Firestore 数据库不存储数据

flutter - flutter 的自定义注解,例如Required

dart - 如何在没有 Scaffold.drawer 的情况下使用 Drawer?

dart - Dart “For Loop” “If Else” “Boolean return”

firebase - 找不到 com.google.firebase :firebase-crashlytics-gradle:17. 0.0-beta01

java - Android Java Firebase 查询对象到 ArrayList 中

flutter - 我需要有关如何保存应用状态的指南。

ios - Flutter 忽略 ffi-1.12.2,因为它的扩展没有构建。试试 : gem pristine ffi --version 1. 12.2

flutter - 异步方法在Flutter中返回null

java - 如何实现观察者以从监听器获取数据?