I have a response in JSON:
{
"data": {
"id": "12-43-abc",
"number": "4",
"name": "Admin Test 1",
"stage": "active",
"sex": "female",
"title": "admin",
"dob": null,
"phoneNumber": "1",
"email": "[email protected]",
"address": null,
"mId": null,
"createdDateTime": "2020-09-17T02:42:10.447Z",
"totalRemain": null,
"carryOverRemain": null,
"fromTime": null,
"toTime": null
}
}
To convert JSON to Object, I create a model:
class User {
String? id;
String? number;
String? name;
String? stage;
String? sex;
String? title;
DateTime? dob;
String? phoneNumber;
String? email;
String? address;
String? mId;
DateTime? createdDateTime;
int? totalRemain;
int? carryOverRemain;
DateTime? fromTime;
DateTime? toTime;
User({
this.id,
this.number,
this.name,
this.stage,
this.sex,
this.title,
this.dob,
this.phoneNumber,
this.email,
this.address,
this.mId,
this.createdDateTime,
this.totalRemain,
this.carryOverRemain,
this.fromTime,
this.toTime});
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'],
number: json['badgeNumber'] ?? "null",
name: json['name'] ?? "null",
stage: json['status'],
sex: json['gender'] ?? "null",
title: json['title'] ?? "null",
dob: DateTime.parse(json['birthDay']),
phoneNumber: json['phone'] ?? "null",
email: json['email'] ?? "null",
address: json['address'] ?? "null",
mId: json['managerId'] ?? "null",
createdDateTime: DateTime.parse(json['createdDateTime']),
totalRemain: json['totalRemain'],
carryOverRemain: json['carryOverRemain'],
fromTime: DateTime.parse(json['fromTime']),
toTime: DateTime.parse(json['toTime'])
);
}
}
I create a signIn method:
Future<Either<Failure, dynamic>> signIn(String number, String password) async {
try {
Map<String, String> bd = {
'number': number,
'password': password
};
final Response res = await dio.post(Endpoint.signIn, data: bd);
if(res.statusCode == 200) {
return Right(User.fromJson(res.data['data']));
}
else {
return Right(res.data['error']);
}
}
catch(e) {
throw e;
return Left(SystemFailure());
}
}
When debugging, the status code is 200 but it throws an exception type 'Null' is not a subtype of type 'String'. I've searched Google for it but still have no answer. No idea what's wrong in my model class. Thanks for your help.
CodePudding user response:
The problem is with dob
, fromTime
and toTime
because they are null
. You can't do DateTime.parse()
on null
. So maybe you can replace this
toTime: DateTime.parse(json['toTime'])
with
toTime: json['toTime'] != null ? DateTime.parse(json['toTime']) : null
for example. The same logic with dob
and toTime
. Probably also with createdDateTime
in case that one happens to be null
as well
CodePudding user response:
you need to decode the JSON
like this:
final decodedJson = json.decode(res);
because the JSON you got from the HTTP request is just a String
you need to decode it to get the Map<String, String>
the, work with it.