Home > Enterprise >  I want to handle dateTime null value in JSON parsing in flutter
I want to handle dateTime null value in JSON parsing in flutter

Time:12-20

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"],
  );

CodePudding user response:

You just need to make a condition like that:

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

CodePudding user response:

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

CodePudding user response:

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"],
  );
  • Related