I send a request to server and when the status code is 200 everything is ok i can decode the returned json, but when the status isn't 200 i have a problem
here's the json of status code 200:
{
"success": true,
"statusCode": 200,
"code": "jwt_auth_valid_credential",
"message": "Credential is valid",
"data": {
"token": "a token",
"id": 42626,
"email": "[email protected]",
"nicename": "",
"firstName": "",
"lastName": "",
"displayName": ""
}
}
i have adjusted the type of data
as a nested structure and it's fine,
the json of else status codes is like this:
{
"success": false,
"statusCode": 403,
"code": "invalid_username",
"message": "Error: The username ** is not registered on this site. If you are unsure of your username, try your email address instead.",
"data": []
}
and here's my problem the returned data
value is an empty array and idk how to handle it.
here's my model class:
class loginpagemodel{
late final message;
late final Data data;
loginpagemodel({
this.message,required this.data });
factory loginpagemodel.fromJson(Map<String , dynamic> parsedJson){
return loginpagemodel(
message: parsedJson['message'],
data: Data.fromJson(parsedJson['data']
),
);
}
}
class Data{
late final id;
late final displayName;
Data({this.id,this.displayName});
factory Data.fromJson(Map<String,dynamic> parsedJson){
return Data(
id: parsedJson['id'],
displayName: parsedJson['displayName'],
);
}
}
Thanks for ur answers in advance.
CodePudding user response:
The problem is when the status code isnt 200 the data
field is List
. A possible solution:
factory loginpagemodel.fromJson(Map<String , dynamic> parsedJson){
return loginpagemodel(
message: parsedJson['message'],
data: Data.fromJson(
parsedJson['data'] == []? // if data is [] (the status code isnt 200)
{} : // empty map
parsedJson['data'] // the data field
),
);
}
CodePudding user response:
You can basically control your data, if it is not empty, you can use. Just one example;
if(myJson["data"].length == 0 ) {
print("there is no data");
}else{
print("there is data: ${myJson["data"].toString()}");
}
CodePudding user response:
You could make data field nullable: Data? data.