I am using Firebase Cloud Messaging with a background message handler, annotated with @pragma(‘vm:entry-point’), in my Flutter app. Inside the background handler, I call getIt as my service locator to obtain the injected AudioPlayer instance. However, I encounter the following error:
An error occurred in your background messaging handler:
Bad state: GetIt: Object/factory with type AudioPlayer is not registered inside GetIt.
(Did you accidentally do GetIt sl=GetIt.instance(); instead of GetIt sl=GetIt.instance;
Did you forget to register it?)
I have registered AudioPlayer with GetIt and injectable, and it works fine in the foreground state handler for Firebase setup. My dependency injection is set up as follows:
Injection file:
final getIt = GetIt.instance;
@InjectableInit()
Future<void> configureDependencies() => getIt.init();
Dependency Module:
@module
abstract class CoreModule {
@lazySingleton
AudioPlayer get audioPlayer => AudioPlayer();
// Other dependencies...
}
The reason is that the this callback is called on a different isolate than your already background app. All variables live only in the isolate where they are created and you can’t access a variable from a different isolate.
why don’t you call configureDependencies at the beginning of your handler so that all your dependencies are registered in this isolate.
because I need to access to that instance that is injected in the main isolate and that appears impossible, so in this case I will search for another solution
thank you a lot @escamoteur
As it won’t be possible to do that directly you could save needed data to share_preferences when your app is being suspened for example and read it back inside the callback