Home > Mobile >  Problem fetching data from my api in flutter
Problem fetching data from my api in flutter

Time:01-14

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

CodePudding user response:

TRY THIS...

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

what you are doing is fetching all the data from the api and then use the data what you want in the widget in your app.

CodePudding user response:

  • 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();
      );

   
  • Related