skip to Main Content

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

3

Answers


  1. You just need to make a condition like that:

    json["CreatedDate"] == null ? null : DateTime.parse(json["CreatedDate"])
    
    Login or Signup to reply.
  2. 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"],
      );
    
    Login or Signup to reply.
  3. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search