skip to Main Content

I have the following code in my flutter app:

MODELS:

APIUser apiUserFromJson(String str) => APIUser.fromJson(json.decode(str));

String apiUserToJson(APIUser data) => json.encode(data.toJson());

class APIUser {
  APIUser({this.id, this.username, this.email, this.role});

  int? id;
  String? username;
  int? email;
  String? role;

  factory APIUser.fromJson(Map<String, dynamic> json) => APIUser(
        id: json["user"]["id"],
        username: json["user"]["username"],
        email: json["user"]["email"],
        role: json["user_role"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "username": username,
        "email": email,
        "role": role,
      };
}


GlobalUser globalUsersFromJson(String str) =>
    GlobalUser.fromJson(json.decode(str));

String globalUsersToJson(GlobalUser data) => json.encode(data.toJson());

class GlobalUser {
  GlobalUser({
    this.users,
  });

  List<APIUser>? users;

  factory GlobalUser.fromJson(Map<String, dynamic> json) => GlobalUser(
        users:
            List<APIUser>.from(json["users"].map((x) => APIUser.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "users": List<dynamic>.from(users!.map((x) => x.toJson())),
      };
}

UPDATED
MY METHOD FOR FETCHING:

Future<dynamic> getGlobalUsers() async {
try {
  var token = storage.read('token');
  final uri = Uri.parse("${ApiConstants.baseUrl}/get_users");
  final headers = {
    HttpHeaders.contentTypeHeader: 'application/json',
    HttpHeaders.authorizationHeader: 'Token $token'
  };
  var response = await http.post(uri,
      headers: headers); // Request Timeout response status code
  **print(response);**

  if (response.statusCode == 200) {
    GlobalUser globalUsers = globalUsersFromJson(response.body);
    return globalUsers;
  }
  if (response.statusCode == 401) {
    return http.Response('Error', 401);
  }
  if (response.statusCode >= 500) {
    return http.Response('Error', 500);
  }
} catch (e) {
  log(e.toString());
}

}

API RESPONSE IN POSTMAN FOR THE URL ASKED IN PREVIOUS METHOD getGlobalUsers:

[
    {
        "user": {
            "id": 16,
            "last_login": "2022-11-27T16:20:42.271178+01:00",
            "username": "user1",
            "email": "[email protected]",
            "date_joined": "2022-11-27T15:30:47.851322+01:00",
            "groups": [],
            "user_permissions": []
        },
        "user_role": "worker"
    }
]

In flutter, if I print the response of this method, I´m getting [], and I´m not sure about what am I doing wrong. The whole Backend API is working OK , as in POSTMan. THE PRINT STATEMENT IN FETCHING METHOD RETURNS NOTHING
Thanks in advance

2

Answers


  1. TRY THIS…

    factory GlobalUser.fromJson(Map<String, dynamic> json) => GlobalUser(
            users:
                List<APIUser>.from(json.map((x) => APIUser.fromJson(x))),
          );
    

    what you are doing is fetching all the data from the API and then using the data that you want in the widget in your app.

    Login or Signup to reply.
    • int? email should be a String? email

    • You need to return List<dynamic> as your API response data is List

    GlobalUser globalUsersFromJson(String str) =>
        GlobalUser.fromJson(json.decode(str)as List<dynamic>);
    
     factory GlobalUser.fromJson(List<dynamic> json) => GlobalUser(
            users:
                 json
            .map((e) => APIUser.fromJson(e as Map<String, dynamic>))
            .toList();
          );
    
       
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search