0

I'd like to convert a dynamic map object on Firestore into Flutter. Below is an example:

The map for blocked users can change. Sometimes, it may contain 3 blocked users enter image description here Other times, it may contain 2. enter image description here

Below is my current code:

    class UserModel {
      String userId;
      String bio;
    ///add in dynamic blockedusers mapping
    }
    
    UserModel(
          {
          this.userId,
          this.bio,
    ///add in dynamic blockedusers mapping
    }
    
    UserModel.fromJson(Map<dynamic, dynamic> map) {
        userId = map['userId'];
        bio = map['bio'];
    ///add in dynamic blockedusers mapping
    }
    
     toJson() {
        return {
          "userId": userId,
          'bio': bio,
    ///add in dynamic blockedusers mapping
    };
    }

Given that the map object changes, is there a way to dynamically map it from Firestore into Flutter or map it from Flutter into Firestore? Thanks in advance!

1
  • Hi Scott. You probable are using it, but to be sure I will ask. Are you using cloud_firestore and firebase_core libraries as dependencies to import and export from/to flutter? Commented Sep 7, 2021 at 12:49

1 Answer 1

1

There are a few ways to do this, the easiest is just storing it as a Map on the UserModel.

Or in dart you can map through them the create a list of strings: List blockedUsers = blockedUsersFromDB.keys.toList().

Or if there is more information create a sub model with a static listfromjson:

class BlockedUser{
  final String id;
  BlockedUser({this.id});

  factory BlockedUser.fromMap(Map map){
    return BlockedUser(id: map['userId']);
  }

  static List<BlockedUser> listFromJson(Map<dynamic, dynamic> json){
    // adjust to your data set or to use the from map function above
    return json.keys.map((user) => BlockedUser(id: user));
  }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.