Search code examples
flutterdart

flutter TimeOfDay to json


I'm working on an alarm clock type application where I need to save time for different days of week.

Something like this:

[
  {
    'day': 'Sunday',
    'time': '11.00 A.M' --> on Sunday the alarm will fire at 11.00 A.M
  }
  {
    'day': 'Monday',
    'time': '1.00 A.M' --> on Monday the alarm will fire at 1.00 A.M
  }
]

This is the model I've written:

class ReminderModel {
  String? dayName;
  TimeOfDay? startTime;
  TimeOfDay? endTime;
  TimeOfDay? frequency;
  TimeOfDay? breakDuration;
  bool? isPending;

  ReminderModel({
    this.dayName,
    this.startTime,
    ...
  });
  factory ReminderModel.fromJson(Map<String, dynamic> json) => ReminderModel(
        dayName: json["dayName"],
        startTime: json["startTime"],
        ...
      );
  Map<String, dynamic> toJson() => {
        "dayName": dayName!,
        "startTime": startTime!.toString(),
        ...
      };
}

I'm using Hive for local db use. Saving is no issue(I guess toString() is correct). But during splash screen I'm loading all the data and this is the error I get:

Unhandled Exception: FormatException: Invalid date format

Since I only need the Time I thought using TimeOfDay() is enough. What am I doing wrong here?

**N.B:**I've not been clear which line causes the error. And honestly my best guess is it't the fromJson() method. I'm sure I'm not parsing it right. That's why when the app loads the data is not getting loaded right


Solution

    1. You are passing wrong keys during parse the data.
    2. Time is coming in string format, you can to convert it to TimeOfDay in fromJson. And one more thing is that flutter doesn't support HH.MM format. Please use HH:MM format