srawlins / timezone

Time zone database and time zone aware DateTime object for Dart.
BSD 2-Clause "Simplified" License
102 stars 53 forks source link

Set location/timezone is not persisted over multiple files #123

Open reesz opened 2 years ago

reesz commented 2 years ago

Version in use: timezone: ^0.7.0-nullsafety.0

Flutter doctor:

[✓] Flutter (Channel stable, 2.5.1, on macOS 11.3 20E232 darwin-x64, locale
    de-DE)
    • Flutter version 2.5.1 at /Users/_/.flutter/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision ffb2ecea52 (9 weeks ago), 2021-09-17 15:26:33 -0400
    • Engine revision b3af521a05
    • Dart version 2.14.2

I'm using the following way with the flutter_native_timezone package to determine the users timezone:

final String timeZoneName = await FlutterNativeTimezone.getLocalTimezone();
tz.setLocalLocation(tz.getLocation(timeZoneName));

One weird thing that seems to happen with my setup since the Flutter 2 upgrade: I'm doing the full timezone init + location setting right at the top of main.dart (which works fine):

tz.initializeTimeZones();
final String timeZoneName = await FlutterNativeTimezone.getLocalTimezone();
tz.setLocalLocation(tz.getLocation(timeZoneName));

and in a helper service in another file notification_helper.dart im using static methods to schedule local notifications using the flutter_local_notifications package. But when I access the tz methods in there:

class NotificationService {
  static tz.TZDateTime toLocalDateTime(DateTime dateTime) {
    print(tz.local);
    return tz.TZDateTime.local(dateTime.year, dateTime.month, dateTime.day, dateTime.hour, dateTime.minute,
        dateTime.second, dateTime.millisecond);
  }
}

and print the tz's local it's reset to UTC which then gives a UTC timezone DateTime from TZDateTime.local instead of the correct one (in my case Europe/Berlin). Oddly this seems to have worked before the Flutter 2 update, since we were using this setup for ~1 year without problems. A dirty fix would be to just re-init and re-set the timezone everytime in the toLocalDateTime method.

Shouldn't there a more elegant way of correctly setting the location over multiple places or am I missing something here?

lucasribolli commented 1 year ago

have you discovered the ideal solution for this?

reesz commented 1 year ago

@lucasribolli sadly not, we've just used the workaround of re-initiating the timezone since then:

    tz.initializeTimeZones();
    final String timeZoneName = await FlutterNativeTimezone.getLocalTimezone();
    tz.setLocalLocation(tz.getLocation(timeZoneName));

before the tz.TZDateTime.local call.