P-J
P-J

Reputation: 219

Invalid Date Format - Flutter/Dart

It might be a simple solution but I have some problems with it. I have JSON response with user data like name, address, and birthday. However, birthDay is empty and I cannot parse it.

Error (only those lines occure):

Exception has occurred.
FormatException (FormatException: Invalid date format
)

I'm using tryParse and DateFormatter with null check but it seems to not work as I expect. Below you'll find part of code and JSON response:

Part of response:


birthDay: "" // as you see it's empty
bioInfo: ""
badges: List(6 items)
agreement5: false

Part of Profile Entity:

class ProfileEntity {

final String birthDay;

ProfileEntity.fromJson(Map<String, dynamic> json)
      : birthDay = json['birthDay'],

}

Part of Profile Model:


class ProfileModel {

final DateTime birthDate;

ProfileModel({@required this.birthDate});

ProfileModel.fromEntities(
    ProfileEntity profileEntity,
  ) : birthDate = DateTime.tryParse(profileEntity.birthDay), //place where I'm getting an error - value is null in this case. 

//here I'm sending it to form field

Map<String, String> toFormFields() {
    return {
      'jform[birthDay]':
          birthDate != null ? DateFormat("yyyy-MM-dd").format(birthDate) : "", //null check
    }
  }

}

Do you have any idea how to get rid of this? (Error message do not provide any info despite what I paste above in error part)

Upvotes: 1

Views: 2619

Answers (2)

Ashutosh Pareek
Ashutosh Pareek

Reputation: 191

DateFormat('dd-MM-yyyy').parse(widget.initialDate);

remember you can change date format according to which you api sends date in my case 'dd-MM-yyy' in your case may be different format.

Upvotes: 0

Rahul
Rahul

Reputation: 5049

DateTime.tryParse does not expect null value.

You can replace this with DateTime.tryParse(profileEntity.birthDay ?? '') which will return null instead of throwing exception.

For ref: tryParse method

Upvotes: 1

Related Questions