如何在数组 flutter Firestore 中添加地图

Mil*_*aro 3 firebase flutter google-cloud-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. 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. 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:

class MemberList {
  final String memberName;
  final int plastics;

  MemberList(this.memberName, this.plastics);

  Map<String, dynamic> toMap() =>
      {"memberName": this.memberName, "plastics": this.plastics};
}
Run Code Online (Sandbox Code Playgroud)

I am trying to save the values inside of this array in my other model:

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

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

 
}
Run Code Online (Sandbox Code Playgroud)

In my database, I have this function that lets users join groups, and here is where I can create my array. First I created a string called 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;
  }
Run Code Online (Sandbox Code Playgroud)

And when a user actually joins this function gets called which takes their displayName and adds it to the member array:

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);
      }
    }
Run Code Online (Sandbox Code Playgroud)

From a visual perspective, this is how my firestore document stores the array now: 在此输入图像描述

But, I need it like this: 在此输入图像描述

Any help would be greatly appreciated as I have a hard time with maps. Thank you.

小智 6

如果直接按照这个模型获取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();
 }
Run Code Online (Sandbox Code Playgroud)

我可能错误地输入了 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,
      };
  }
Run Code Online (Sandbox Code Playgroud)