Home > Enterprise >  Type 'DateTime' is not a subtype of type 'TZDateTime?' in Flutter Project
Type 'DateTime' is not a subtype of type 'TZDateTime?' in Flutter Project

Time:08-25

in Terminal error is showing Reading a NULL string not supported here.

 DateTime _combineDateWithTime(DateTime date, TimeOfDay time) {
    if (date == null && time == null) {
      return null;
    }
    final dateWithoutTime =
        DateTime.parse(DateFormat("y-MM-dd hh:mm:ss").format(date));
    return dateWithoutTime
        .add(Duration(hours: time.hour, minutes: time.minute));

  }

enter image description here

CodePudding user response:

Proposed solution:

DateTime? _setTimeOfDate(DateTime? date, TimeOfDay? time) {
  if (date == null || time == null) {
    return null;
  }
  return DateTime(date.year, date.month, date.day, time.hour, time.minute);
}

Have fun.

Explanation

First of all, if you're working with null safety, you should allow the return type to be null:

DateTime? _combineDateWithTime(DateTime date, TimeOfDay time) { ... }

(mind the ? in the return type). In that case, you won't be needing the null checks in the beginning.

If you allow null as parameters, I'd suggest to check for null with an || instead of a &&.

DateTime? _combineDateWithTime(DateTime? date, TimeOfDay? time) {
  if (date == null || time == null) {
    return null;
  }
  ...
}

IMHO, without judgement, formatting and parsing the date is a bit strange. I assume the combineDateWithTime function should actually set the date to a specific time, right? (Side note, i'd rename the method to setTimeOfDate or similar, to make the naming more specific.)

Please correct me if I'm wrong with my interpretation of what the method should do, but if i assume correctly, you could get the result by using the proposed method above.

CodePudding user response:

DateTime.parse expects a string to be present in a format called "TZDateTime" and the output of Dateformat is not in that format, refer this for valid formats: https://api.flutter.dev/flutter/dart-core/DateTime/parse.html

Btw, I don't understand why you are converting DateTime to DateFormat and back to DateTime again?

  • Related