Nazhim
Nazhim

Reputation: 17

I want to handle dateTime null value in JSON parsing in flutter

I need help handling the null values for DateTime JSON parse. Since some of the data does not have createDate, I have a problem showing the data this is my code:

factory OfaModel.fromJson(Map<String, dynamic> json) => TestModel(
    createdDate: DateTime.parse(json["CreatedDate"]),
    recordtypeBm: json["recordtype_bm"],
    amsCustodialHistoryBm: List<String>.from(json["AMSCustodialHistoryBM"].map((x) => x)),
    subjectCode: json["SubjectCode"]
    recordtypeBi: json["recordtype_bi"],
  );

Upvotes: 0

Views: 782

Answers (3)

Meshkat Shadik
Meshkat Shadik

Reputation: 337

You can use DateTime.tryParse()

createdDate : DateTime.tryParse(json["CreatedDate"] ?? ''),
//DateTime.parse('') -> Returns (Uncaught Error: FormatException: Invalid date format)
//DateTime.tryParse('') -> Returns null instead of Exception

Upvotes: 1

Jay
Jay

Reputation: 261

just check if it's not or not,

factory OfaModel.fromJson(Map<String, dynamic> json) => TestModel(
    createdDate:json["CreatedDate"] != null ? DateTime.parse(json["CreatedDate"]) : null,
    recordtypeBm: json["recordtype_bm"],
    amsCustodialHistoryBm: List<String>.from(json["AMSCustodialHistoryBM"].map((x) => x)),
    subjectCode: json["SubjectCode"]
    recordtypeBi: json["recordtype_bi"],
  );

Upvotes: 0

You just need to make a condition like that:

json["CreatedDate"] == null ? null : DateTime.parse(json["CreatedDate"])

Upvotes: 1

Related Questions