简体   繁体   English

如何在数组 flutter Firestore 中添加 map

[英]How to add a map within an array flutter Firestore

So I have this array in firestore called members and what it does so far is simply hold a list of user display names who have joined the list.所以我在 firestore 中有一个名为 members 的数组,到目前为止它所做的只是保存已加入列表的用户显示名称列表。 However, what I need is to be able to create a map within this array that will hold two values unique to each member, their name, and the number of plastics they collected.但是,我需要的是能够在此数组中创建一个 map,它将保存每个成员的两个唯一值、他们的姓名和他们收集的塑料数量。 I'm quite confused about how to accomplish this.我对如何实现这一点感到很困惑。

Here is what I think a map structure should look like, I'm probably wrong though:这是我认为 map 结构应该是什么样子的,不过我可能错了:

class MemberList {
  final String memberName;
  final int plastics;

  MemberList(this.memberName, this.plastics);

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

I am trying to save the values inside of this array in my other model:我正在尝试将此数组内的值保存在我的另一个 model 中:

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

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

 
}

In my database, I have this function that lets users join groups, and here is where I can create my array.在我的数据库中,我有这个 function 允许用户加入组,在这里我可以创建我的数组。 First I created a string called displayName:首先,我创建了一个名为 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;
  }

And when a user actually joins this function gets called which takes their displayName and adds it to the member array:当一个用户实际加入时,这个 function 被调用,它获取他们的 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);
      }
    }

From a visual perspective, this is how my firestore document stores the array now:从视觉的角度来看,这就是我的 firestore 文档现在存储数组的方式: 在此处输入图像描述

But, I need it like this:但是,我需要这样的: 在此处输入图像描述

Any help would be greatly appreciated as I have a hard time with maps.任何帮助将不胜感激,因为我很难使用地图。 Thank you.谢谢你。

It will work if you directly get the Group class according to this model. You don't need to specifically MemberList Model. for example;直接根据这个model得到Group class就可以了,不需要具体MemberList Model。例如;

   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();
 }

I may have typed the firebase call method incorrectly.我可能输入了错误的 firebase 调用方法。 but the model has to be like this.但是 model 必须是这样的。

   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,
      };
  }

Right now, your member list is a String list.现在,您的成员列表是一个String列表。 But you want to add memberName and plastics properties.但是您想添加memberNameplastics属性。 So, you need to use a member model like this:因此,您需要像这样使用成员 model:


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,
    };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM