Search code examples
flutterflutter-workmanager

how to access singleton objects inside Workmanager.executeTask's callback using flutter-workmanager


Creating List<String> mainList globally and adding one item in main() function. But inside the Workmanager.executeTask's callback mainList's lenth is still 0. Even the hashCode of the mainList is different.

  • Why this is happening?
  • How make the mainList as Singleton?
  • Tried printing the Isolate.current.debugName, it's always 'main'.
List<String> mainList=[];
void callbackDispatcher() {
  Workmanager.executeTask((task, inputData) {
    print("mainList.length=${mainList.length}"); // always length is 0
    print("Isolate.current.debugName = ${Isolate.current.debugName}");
    return Future.value(true);
  });
}

void main() {
  Workmanager.initialize(
    callbackDispatcher,
    isInDebugMode: true,
  );
  mainList.add("String1");
  print("mainList.length=${mainList.length}"); // length is 1
  print("Isolate.current.debugName = ${Isolate.current.debugName}");
  Workmanager.registerPeriodicTask("1", "simpleTask");
  runApp(MyApp());
}

Solution

  • In ListenableWorker.startWork() a new FlutterEngin instance is created every time and executing Workmanager.executeTask's callback.

    So no way for using singleton objects.

    BackgroundWorker.kt