Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

 
}

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

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

From a visual perspective, this is how my firestore document stores the array now: enter image description here

But, I need it like this: enter image description here

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

like image 447
Milly Alfaro Avatar asked Feb 20 '26 19:02

Milly Alfaro


1 Answers

It will work if you directly get the Group class according to this model. You don't need to specifically MemberList Model. for example;

   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. but the model has to be like this.

   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,
      };
  }
like image 128
hasan karaman-goodsoft Avatar answered Feb 23 '26 11:02

hasan karaman-goodsoft



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!