tjarvstrand / flutter_timezone

A fork of https://github.com/pinkfish/flutter_native_timezone
Apache License 2.0
42 stars 29 forks source link

Getting crash on iOS device when plugin is run from a background isolate #21

Closed udoy-touhid closed 8 months ago

udoy-touhid commented 8 months ago

I'm using workmanager to trigger workManagerCallback repeatedly in the background like below.

@pragma('vm:entry-point')
void workManagerCallback() {
  WidgetsFlutterBinding.ensureInitialized();
  DartPluginRegistrant.ensureInitialized();
  log("workManagerCallback");

  try {
    _configureLocalTimeZone().then((value) async { // **crash on this line
    Workmanager().executeTask(handle);
    });
  } catch (exp) {
    log(exp.toString());
  }
}

Future<bool> handle(task, inputData) async {
  try {
    //implementation
    return Future.value(true);
  } catch (exception) {
    print(exception.toString());
    throw exception;
  }
}

Future<void> _configureLocalTimeZone() async {
  if (kIsWeb || Platform.isLinux) {
    return;
  }
  tz.initializeTimeZones();
  final String timeZoneName = await FlutterTimezone.getLocalTimezone();
  tz.setLocalLocation(tz.getLocation(timeZoneName));
}

But I'm getting below crash. I think the plugin is not working on iOS while called from a background isolate

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: MissingPluginException(No implementation found for method getLocalTimezone on channel flutter_timezone)
#0      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:320:7)
tjarvstrand commented 8 months ago

Hi! AFAIK, plugins that use platform channels generally don't work from isolates other than the main isolate. I would probably either fetch the timezone before the new isolate is started (since it's unlikely to change) or set up messaging so that you can call this as an RPC to the main isolate.

Alternatively, you can look into if flutter_isolate solves your problem, though that is a bit more heavy handed.

Ultimately, this behavior is inherent in Flutter and not something I can fix in flutter_timezone. As such, I'll close this issue. Feel free to let me know if there is in fact a problem that you see in this package 🙂

udoy-touhid commented 8 months ago

@tjarvstrand thanks a lot for pointing to the right directions. Really appreciate it.