Home > OS >  Flutter model doesnt work with different responses
Flutter model doesnt work with different responses

Time:10-30

I have a Fluter Model User

class User {
  String id;
  String name;
  String email;
  String image;

  User({
    this.id = "",
    this.name = "",
    this.email = "",
    this.image = "",
  });

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      id: json['id'],
      name: json['name'],
      email: json['email'],
      image: json['image'],
    );
  }

  Map toMap() {
    var map = Map<String, dynamic>();

    map['id'] = id;
    map['name'] = name;
    map['email'] = email;
    map['image'] = image;

    return map;
  }
}

And I have a flutter LoginResult that calls user model when I do login

import 'User.dart';

class LoginResult {
  String message;
  String? token;
  User? user;

  LoginResult({
    this.message = "",
    this.token,
    this.user,
  });

  factory LoginResult.fromJson(Map<String, dynamic> json) {
    if (json['user'] != null) {
      return LoginResult(
        message: json['message'],
        user: User.fromJson(json['user']),
        token: json['token'],
      );
    } else {
      return LoginResult(
        message: json['message'],
        token: json['token'],
      );
    }
  }

  Map toMap() {
    var map = Map<String, dynamic>();

    map['message'] = message;
    map['user'] = user;
    map['token'] = token;

    return map;
  }
}

When I do login, the parsing response body in LoginResults works fine with this result json

{
    "message": "logged in success",
    "user": {
        "rol": 100,
        "image": "83f124c1-5a46-469c-8de7-11a90c506a44.jpg",
        "_id": "6105c3c8bf76720bfa2e31e9",
        "name": "Guillermo Canales Justo",
        "email": "[email protected]",
        "password": "$2b$10$Z5.RMoRHeyKt7cdFrtubbOzEGjGvHhU19UQEV.mA/ZSunIXqKhYz.",
        "__v": 48,
        "created": "2021-09-18T06:52:40.995Z",
        "id": "6105c3c8bf76720bfa2e31e9"
    },
    "token": "eyJhbGciOiJIUzI..."
}

But when I update profile user and returns this json, User.fromJson(json_decode(response.body)) returns properties null.

email:null
id:null
image:null
name:null
hashCode:258164629
runtimeType:Type (User)

with this json response

{
    "user": {
        "rol": 100,
        "image": "595ccd2c-1c37-42a7-904f-fdc73b5f89b0.jpg",
        "_id": "6105c3c8bf76720bfa2e31e9",
        "name": "Guillermo Canales",
        "email": "[email protected]",
        "password": "$2b$10$Z5.RMoRHey...",
        "__v": 48,
        "created": "2021-09-18T06:52:40.995Z",
        "id": "6105c3c8bf76720bfa2e31e9"
    }
}

I cant understand what's wrong with the second parsing.

CodePudding user response:

you will have to get the Users from the json.

change this line

User.fromJson(json_decode(response.body))

to

User.fromJson(json_decode(response.body)['user'])
  • Related