jsonflutterresponse

how to convert a Response object into a model class in flutter


My server is returning a response object that I want to convert it to a model class but I'm having this error message when I tried to type cast the response into my model. I have checked other suggestions here but still can't get the one that gives me exactly what I want.The response that the server returned is as shown in the model class called AuthResponse.The logcat returned this error message; Unhandled Exception: type 'Response' is not a subtype of type 'Map<String, dynamic>' in type cast

class ApiClient {
  static Map<String, String> header = <String, String>{
    'Authorization': 'Bearer: ${AppUrlConstant.TOKEN}',
    'content-type': 'application/json',
    'api-key': AppUrlConstant.API_KEY,
    'Accept': 'application/json'
  };

  static Future<Response> postData(String endpoint, dynamic body) async {
    var url = Uri.parse(AppUrlConstant.BASE_URL + endpoint);
    try {
      Response response =
          await post(url, body: json.encode(body), headers: header);
      print("The post response returns ${response.body}");
      return response;
    } catch (e) {
      print(e.toString());
      return Response(e.toString(), 1);
    }
  }
}

class AuthRepository {

  static Future<AuthResponse> login(LoginModel loginModel) async {
    var response =
        await ApiClient.postData(AppUrlConstant.LOGIN_URL, loginModel.toJson());
    print("The login response is $response");
    return AuthResponse.fromJson(response as Map<String, dynamic>);
  }
}

class AuthResponse {
  String? terminus;
  String? status;
  ReturnResponse? response;

  AuthResponse({this.terminus, this.status, this.response});

  factory AuthResponse.fromJson(Map<String, dynamic> json) => AuthResponse(
      terminus: json["terminus"],
      status: json["status"],
      response: ReturnResponse.fromJson(json["response"]));
}

class ReturnResponse {
  int? code;
  String? title;
  String? message;
  Data? data;

  ReturnResponse({this.code, this.title, this.message, this.data});

  factory ReturnResponse.fromJson(Map<String, dynamic> json) => ReturnResponse(
      code: json["code"],
      title: json["title"],
      message: json["message"],
      data: Data.fromJson(json["data"]));
}

class Data {
  String? token;
  AdminResponse? admin;

  Data({this.token, this.admin});

  factory Data.fromJson(Map<String, dynamic> json) =>
      Data(token: json["token"], admin: AdminResponse.fromJson(json["admin"]));
}

class AdminResponse {
  int? id;
  String? firstName;
  String? email;
  String? phoneNumber;
  String? emailVerified;
  String? createdAt;
  String? updatedAt;

  AdminResponse(
      {this.id,
      this.firstName,
      this.email,
      this.phoneNumber,
      this.emailVerified,
      this.createdAt,
      this.updatedAt});

  Map<String, dynamic> toJson() {
    Map<String, dynamic> data = <String, dynamic>{};
    data["id"] = id;
    data["first_name"] = firstName;
    data["email"] = email;
    data["email_verified"] = emailVerified;
    data["created_at"] = createdAt;
    data["updated_at"] = updatedAt;

    return data;
  }

  factory AdminResponse.fromJson(Map<String, dynamic> json) => AdminResponse(
      id: json["id"],
      firstName: json["first_name"],
      email: json["email"],
      phoneNumber: json["phone_number"],
      emailVerified: json["email_verified"],
      createdAt: json["created_at"],
      updatedAt: json["updated_at"]);
}

Solution

  • You just missing deserialization of response body.

    this is my method for refer

    Future<ApiBaseResponse> getArtistData(String artistName) async {
    var response = await http.get(
      Uri.parse(
        'url',
      ),
      headers: ApiParameters.headers,
    );
    if (response.statusCode == 200) {
      return ApiBaseResponse.fromJson(
          jsonDecode(response.body) as Map<String, dynamic>);
    } else {
      throw Exception('Api not Connected');
    }}
    

    you modified code

     class AuthRepository {
    
      static Future<AuthResponse> login(LoginModel loginModel) async {
        var response =
            await ApiClient.postData(AppUrlConstant.LOGIN_URL, loginModel.toJson());
        print("The login response is $response");
        return AuthResponse.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
      }
    }
    

    go to official docs for more info