在flutter中从我的API获取数据时出现问题

bqucvtff  于 2023-01-18  发布在  Flutter
关注(0)|答案(2)|浏览(128)

我的flutter应用程序中有以下代码:
型号:

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())),
      };
}

已更新我的获取方法:

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

}
在Postman中API响应在先前方法getGlobalUsers中请求的URL:

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

在flutter中,如果我打印这个方法的响应,我得到的是[],我不确定我做错了什么。整个后端API工作正常,就像在POSTMan中一样。petching方法中的PRINT语句返回什么都没有。提前感谢

q0qdq0h2

q0qdq0h21#

  • int? email应该是一个
  • 您需要返回List<dynamic>,因为您的API响应数据是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();
      );
nle07wnf

nle07wnf2#

试试这个...

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

您所做的是从API获取所有数据,然后在应用的小部件中使用所需的数据。

相关问题