【问题标题】:How to add a map within an array flutter Firestore如何在数组颤振Firestore中添加地图
【发布时间】:2021-03-18 12:07:04
【问题描述】:

所以我在 firestore 中有一个名为 members 的数组,到目前为止它所做的只是保存已加入该列表的用户显示名称的列表。然而,我需要的是能够在这个数组中创建一个地图,该地图将保存每个成员唯一的两个值、他们的名字和他们收集的塑料数量。我很困惑如何做到这一点。

我认为地图结构应该是这样的,但我可能错了:

class MemberList {
  final String memberName;
  final int plastics;

  MemberList(this.memberName, this.plastics);

  Map<String, dynamic> toMap() =>
      {"memberName": this.memberName, "plastics": this.plastics};
}

我正在尝试将此数组中的值保存在我的其他模型中:

class Group {
  String id;
  String name;
  String admin;
  List<String> members;

  Group({this.id, this.name, this.admin, this.members});

 
}

在我的数据库中,我有一个允许用户加入组的功能,在这里我可以创建我的数组。首先,我创建了一个名为 displayName 的字符串:

Future<String> joinGroup(
      String groupId, String userUid, String displayName) async {
    String retVal = 'error';
    List<String> members = List();
    try {
      members.add(displayName);
      await _firestore.collection('Groups').doc(groupId).update({
        'members': FieldValue.arrayUnion(members),
      });
      final uid = FirebaseAuth.instance.currentUser.uid;
      await _firestore.collection('UserNames').doc(uid).update({
        'groupId': groupId,
      });
      retVal = 'success';
    } catch (e) {}
    return retVal;
  }

当用户真正加入时,这个函数会被调用,该函数获取他们的 displayName 并将其添加到成员数组中:

void _joinGroup(BuildContext context, String groupId) async {
      String uid = auth.currentUser.uid.toString();
      final CollectionReference users =
          FirebaseFirestore.instance.collection('UserNames');
      final name = await users.doc(uid).get();

      final result = name.data()['displayName'];
      String _returnString =
          await GroupDatabase().joinGroup(groupId, uid, result);

      if (_returnString == 'success') {
        Navigator.of(context)
            .pushAndRemoveUntil(groupPageView.route, (route) => false);
      }
    }

从视觉的角度来看,这就是我的 firestore 文档现在存储数组的方式:

但是,我需要这样:

任何帮助将不胜感激,因为我很难使用地图。谢谢。

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:

    如果按照这个模型直接获取Group类就可以了。您不需要专门为 MemberList 模型。 例如;

       await _firestore.collection('Groups').then(value){
    
       Map<String, dynamic> data = json.decode(value);
    
        List<dynamic> result = data['groups'];
       List<Groups > groups =
         result.map((f) => Groups .fromJson(f)).toList();
     }
    

    我可能输入了不正确的 firebase 调用方法。但是模型必须是这样的。

       import 'dart:convert';
    
    
       Groups cargoPriceListModelFromJson(String str) =>
        Groups.fromJson(json.decode(str));
    
     String cargoPriceListModelToJson(Groups data) => json.encode(data.toJson());
    
    class Groups {
         String id;
         String name;
         String admin;
         List<Member> members;
    
     Groups({
        this.id,
        this.name,
        this.admin,
       this.members,
      });
    
      factory Groups.fromJson(Map<String, dynamic> json) => Groups(
            id: json["id"] == null ? null : json["id"],
            name: json["name"] == null ? null : json["name"],
           admin: json["admin"] == null ? null : json["admin"],
           members: json["members"] == null
            ? null
            : List<Member>.from(json["members"]
                .map((x) => Member.fromJson(x))),
         );
    
      Map<String, dynamic> toJson() => {
        "id": id == null ? null : id,
        "name": name == null ? null : name,
        "toCountyId": admin == null ? null : admin,
        "members": members == null
            ? null
            : List<dynamic>.from(members.map((x) => x.toJson())),
        };
     }
    
     class Member {
       String memberName;
       int plastics;
    
    
     Member({
       this.memberName,
       this.plastics,
    
      });
    
    factory Member.fromJson(Map<String, dynamic> json) =>
        Member(
          memberName: json["memberName"] == null ? null : json["memberName"],
        
          plastics: json["plastics"] == null ? null : json["plastics"],
          ) ;
    
    Map<String, dynamic> toJson() => {
          "memberName": memberName == null ? null : memberName,
       
           "plastics": plastics == null ? null : plastics,
          };
      }
    

    【讨论】:

      【解决方案2】:

      现在,您的成员列表是String 列表。但是您想添加 memberNameplastics 属性。所以,你需要使用这样的成员模型:

      
      import 'dart:convert';
      
      MemberModel memberModelFromJson(String str) => MemberModel.fromJson(json.decode(str));
      
      String memberModelToJson(MemberModel data) => json.encode(data.toJson());
      
      class MemberModel {
          MemberModel({
              this.members,
          });
      
          List<Member> members;
      
          factory MemberModel.fromJson(Map<String, dynamic> json) => MemberModel(
              members: json["members"] == null ? null : List<Member>.from(json["members"].map((x) => Member.fromJson(x))),
          );
      
          Map<String, dynamic> toJson() => {
              "members": members == null ? null : List<dynamic>.from(members.map((x) => x.toJson())),
          };
      }
      
      class Member {
          Member({
              this.memberName,
              this.plastics,
          });
      
          String memberName;
          int plastics;
      
          factory Member.fromJson(Map<String, dynamic> json) => Member(
              memberName: json["memberName"] == null ? null : json["memberName"],
              plastics: json["plastics"] == null ? null : json["plastics"],
          );
      
          Map<String, dynamic> toJson() => {
              "memberName": memberName == null ? null : memberName,
              "plastics": plastics == null ? null : plastics,
          };
      }
      

      【讨论】:

        猜你喜欢
        • 2020-10-23
        • 2019-02-25
        • 2020-10-28
        • 2018-10-31
        • 1970-01-01
        • 2021-07-21
        • 2021-11-09
        • 2019-11-19
        • 1970-01-01
        相关资源
        最近更新 更多