gpt4 book ai didi

android - 调用api时如何处理map null对象

转载 作者:IT王子 更新时间:2023-10-29 07:23:14 24 4
gpt4 key购买 nike

如果 status 不是 200,我如何管理服务器响应。

@JsonSerializable(nullable: false)
class LoginResponse {
final String error;
final int status;
final List<User> userList;
LoginResponse({this.error, this.status, this.userList});

factory LoginResponse.fromJson(Map repJson){

List<dynamic> userListResp=repJson['userData'];
List<User> userList=userListResp.map((e)=>User.fromUser(e)).toList();
int s=repJson['status'];
if(s==200){
return LoginResponse(error:repJson['error'],status: repJson['status'],userList:userList);
} else{
return LoginResponse(error:repJson['error'],status: repJson['status']);
}}}

class User{
String cust_id;
String cust_name;
String cust_email;
String cust_mob;

User({this.cust_id,this.cust_name,this.cust_email,this.cust_mob});
factory User.fromUser(Map userJson){
return User(cust_id: userJson['cust_id'],cust_name: userJson['cust_name'],
cust_email: userJson['cust_email'],cust_mob: userJson['cust_mob']);
}
}

发生错误时的服务器响应

{"error":"1","status":201,"message":"Entered email id already exist in our records"}

成功时服务器响应

  {
"error":"0",
"status":200,
"userData":[
{
"cust_id":"87",
"cust_name":"kio",
"cust_email":"kio1@kio.com",
"cust_gend":null,
"cust_dob":null,
"cust_mob":"098998899889588",
"cust_pass":"e10adc3949ba59abbe56e057f20f883e",
"cust_age":null,
"device_type":"android",
"device_token":"eNWqzDwxqsQ:APA91bF-uK1MI11D3SgHGSw7Omv1imjDrPKBBCrN9JgmyJppHsNVeG5l56EkCCd5ZMaxL_ehQzVhtoEj0fTNB55wYGJt5BqYVvwfAb7HrBqwb_21M6VFPuF6LQINkvE1offQgZYweROO",
"status":"0",
"createAt":"2019-01-31 18:45:19",
"updatedAt":"0000-00-00 00:00:00",
"login_type":"",
"login_id":null,
"is_guest":"0",
"auth_token":"",
"forgot_token":null
}]
}

当用户数据不存在或为空时如何管理,我尝试在状态代码为 201 但仍然显示时进行管理

NoSuchMethodError: The method 'map' was called on null.

最佳答案

要修复您的代码,请将 userList 映射移动到 if block 中。这样你将解析只有状态码为 200 的响应。

int s=repJson['status'];
if (s==200) {
List<dynamic> userListResp=repJson['userData'];
List<User> userList=userListResp.map((e)=>User.fromUser(e)).toList();
return LoginResponse(error:repJson['error'], status:repJson['status'], userList:userList);
} else {
return LoginResponse(error:repJson['error'], status:repJson['status']);
}

但是,您可能不想处理模型中的错误。最好在执行请求后检查错误,然后再决定是否要解析响应。

像这样的东西会更容易处理并且不会污染你的模型对象:

final response = await client.get(requestUrl);
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
final loginResponse = LoginResponse.fromJson(json.decode(response.body));

// ...
} else {
// If that call was not successful, throw an error or parse the error object.
throw Exception('Failed to login');

// ...
}

关于android - 调用api时如何处理map<dynamic> null对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54461953/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com