1
class User {
  final String? name;
  final int? age;
  final Map? userAuuth;

  User({this.name, this.age, this.userAuuth});

  Map<String, dynamic> toMap() {
    return {'name': name, 'age': age, 'userAuuth': userAuuth};
  }

  User.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        age = json[22],
        userAuuth = json['userAuuth'];

  Map<String, dynamic> toJson() => {
        'name': name,
        'age': age,
        'userAuuth': userAuuth,
      };
}

class ModelTest {
  Map<String, dynamic> a;

  aa() {
    var a = User().toMap();
    userAuth();
  }
}

I have a User value of 'name': 'aaa', 'age': 23, 'userAuuth': {'aa': 'bb"}. And, I am trying to insert this value to Map<String, dynamic> a inside the class ModelTest.

I've tried many things and I also read that toMap(){} function would do it. But, I could not figure how to apply this method to a here. How can I assign the Map type to a variable using model?

1 Answer 1

2

This is one solution for your request. The problem that you can find is that when you create the user your map can be null and if that is the case you are not able to add any fields in the map. I would recommend if you want to always have a value in your map is to check in the constructor if you do not pass a map to at least instance a new empty map so you can after insert any value, but I'm not sure the solution you are looking for so I followed your class with the possibility that it can be null the map.

class User {
  final String? name;
  final int? age;
  final Map? userAuuth;

  User({this.name, this.age, this.userAuuth});

  User copyWith({
    String? name,
    int? age,
    Map? userAuuth,
  }) =>
      User(
        age: age ?? this.age,
        name: name ?? this.name,
        userAuuth: userAuuth ?? this.userAuuth,
      );

  Map<String, dynamic> toMap() {
    return {'name': name, 'age': age, 'userAuuth': userAuuth};
  }

  User.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        age = json[22],
        userAuuth = json['userAuuth'];

  Map<String, dynamic> toJson() => {
        'name': name,
        'age': age,
        'userAuuth': userAuuth,
      };
}

  void main() {
  var a = User();

  a = a.copyWith(userAuuth: <String, dynamic>{'aa': 'bb'});
  a.userAuuth!['bb'] = 'aa';
 
  print(a.userAuuth);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I put null for just testing. Was lazy to put any value haha. Thank you so much! it workd!

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.