Unable to use Get It background callback

602 Views Asked by At

I have a flutter app that has a background listener but I keep getting an Unhanded exception.

Here is my main()

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  setupLocator();
  await HomeWidget.registerBackgroundCallback(backgroundCallback);
  runApp(const MyApp());
}

here is my setupLocator():

GetIt locator = GetIt.instance;

void setupLocator() {
  locator.registerLazySingleton(() => PreferenceProvider());
  locator.registerLazySingleton(() => CurrencyApi.create());
  locator.registerLazySingleton(() => BackupCurrencyApi.create());
  locator.registerLazySingleton<Repository>(() => RepositoryImpl(locator<PreferenceProvider>(), locator<CurrencyApi>(),locator<BackupCurrencyApi>()));
  ...
}

and here is my backgroundCallback:

Future<void> backgroundCallback(Uri? uri) async {
  Repository repository = locator<RepositoryImpl>();
  ...
}

I get the following error where I try to retrieve the Repository in the background call:

E/flutter (11326): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: 'package:get_it/get_it_impl.dart': Failed assertion: line 372 pos 7: 'instanceFactory != null': Object/factory with type RepositoryImpl is not registered inside GetIt. E/flutter (11326): (Did you accidentally do GetIt sl=GetIt.instance(); instead of GetIt sl=GetIt.instance;

1

There are 1 best solutions below

0
renatogp On

You need to annotate your callback function with @pragma('vm:entry-point') and ensure all dependencies are initialized (such as GetIt).

More details at https://github.com/ABausG/home_widget/pull/99