How to handle dates if they are null on Dart?

Viewed 4633

I am trying to decode a field called noteLastUpdateDate with DateTime.parse() from JSON but it is a nullable field so if it is null DateTime.parse() method throws an exception like this:

Unhandled Exception: FormatException: Invalid date format.

Do you have any recommendations to fix this?

Here is the code: enter image description here

3 Answers

Are you expecting note_last_update_date to be updated before checking it?

You can use a try/on clause to handle null format exceptions:

...
try:
 parsedJSON['note_text'].toString()
 DateTime.parse(parsedJSON['note_last_update_date'].toString())
on FormatException:
 print('Invalid format - datetime is null')
...

To avoid NRE(Null Reference Exception) you need to write something like:

return Note(
  parsedJson[note_text].toString),
  parsedJson['note_last_update_date']==null? 
             null
             :DateTime.parse(parsedJson['note_last_update_date']);

But I prefer to use package json_annotation for json parsing or json2dart tool for avoiding such mistakes when working with json

Related