Home > Software engineering >  type 'String' is not a subtype of type 'Map<String, dynamic>' on a fromJso
type 'String' is not a subtype of type 'Map<String, dynamic>' on a fromJso

Time:10-21

I am trying to do a POST call to my API, with an email and a password.
This returns a 'User' with id, email, country and a token but when trying to pass the received JSON back to a 'User' I get the 'type 'String' is not a subtype of type 'Map<String, dynamic>'' error.

This is my JSON response:

{"id":1,"email":"email","country":"country","token":"token}

This is the function that I am using to call the API:

Future<User> createUser() async {
String email = _emailController.text;
String password = _passwordController.text;
final response =
    await ApiClient().post("/register", RegisterDTO(email, password));
return User.fromJson(response); // line which gets the error

This is the User model which has the fromJson method:

class User {
  int? id;
  String? email;
  String? country;
  String? token;

  User({this.id, this.email, this.country, this.token});

  User.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    email = json['email'];
    country = json['country'];
    token = json['token'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['email'] = this.email;
    data['country'] = this.country;
    data['token'] = this.token;
    return data;
  }
}

I am very new to flutter and dart so if someone can help me, or send me in the right direction I will greatly appreciate it!

CodePudding user response:

Instead of this:

return User.fromJson(response); 

try this:

return User.fromJson(jsonDecode(response));
  • Related