Daniel Klauser
Daniel Klauser

Reputation: 454

Workmanager and get_it for notification purposes

We are using get_it^7.2.0 and workmanager^0.4.1 to do dependency injection (get_it) and scheduling of the backgroundtask (workmanager).

The problem occurs after wanting the registered class inside the workmanager.executeTask() function.

final sl = GetIt.instance;
...
sl.registerLazySingleton<BackgroundRunner>(() => BackgroundRunnerImpl(tasks: sl()));
...

After registering, which all happens inside async functions, I want the object by calling :

void initializeBackgroundTask() {
     Workmanager().initialize(callbackDispatcher, isInDebugMode: false);
     Workmanager().registerPeriodicTask("1", "simplePeriodicTask",
         frequency: Duration(minutes: 45), initialDelay: Duration(seconds: 10));
}

void callbackDispatcher() {
     BackgroundRunner backgroundRunner = di.sl.get<BackgroundRunner>();
     Workmanager().executeTask((task, inputData) {
     // Does Workload
     backgroundRunner.runBackground();
     return Future.value(true);
     });
}

I'll get the following exception everytime the callbackDispatcher is calles by the Workmanager.

E/flutter ( 6388): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: 'package:get_it/get_it_impl.dart': Failed assertion: line 372 pos 7: 'instanceFactory != null': Object/factory with type BackgroundRunner is not registered inside GetIt. E/flutter ( 6388): (Did you accidentally do GetIt sl=GetIt.instance(); instead of GetIt sl=GetIt.instance; E/flutter ( 6388): Did you forget to register it?)

Where do I make a mistake?

Upvotes: 1

Views: 993

Answers (1)

Daniel Klauser
Daniel Klauser

Reputation: 454

You have to register them again in the background to have them available!

void callbackDispatcher() {
  Workmanager().executeTask((task, inputData) async {
    // Does Workload
    await Firebase.initializeApp();
    await di.init();
    BackgroundRunner backgroundRunner = di.sl.get<BackgroundRunner>();
    backgroundRunner.runBackground();
    return Future.value(true);
  });

Upvotes: 1

Related Questions