简体   繁体   中英

Flutter's GetIt with the app in background

I'm having issues with using GetIt while the app is in background. With the app is in focus everything works great but the moment I switch focus everything breaks. What's my error here?

I'm using GetIt 6.1.1, flutter 2.0.5, here's the stacktrace

I/flutter ( 5125): FlutterFire Messaging: An error occurred in your background messaging handler:
I/flutter ( 5125): 'package:get_it/get_it_impl.dart': Failed assertion: line 315 pos 7: 'instanceFactory != null': Object/factory with  type NotificationCubit is not registered inside GetIt. 
I/flutter ( 5125): (Did you accidentally do GetIt sl=GetIt.instance(); instead of GetIt sl=GetIt.instance;
I/flutter ( 5125): Did you forget to register it?)

Here's my GetIt setup

get_it.dart

GetIt getIt = GetIt.instance;

void setupGetIt() {
  getIt.registerSingleton<NotificationCubit>(NotificationCubit());
}

main.dart

void main() async {
  // some other methods
  setupGetIt();
  runApp(MyApp());
}

And the method that throws the error.

void _handleMessage(RemoteMessage message) {
  getIt
      .get<NotificationCubit>()
      .addNotification(NotificationClassName.fromRemoteMessage(message));

  _displaySnackBar(message);
}

You need to call setupGetIt(); again in your _handleMessage , the code becomes:

void _handleMessage(RemoteMessage message) {
   
   //Add it here
   setupGetIt();
   getIt
    .get<NotificationCubit>()
    .addNotification(NotificationClassName.fromRemoteMessage(message));

  _displaySnackBar(message);
 }

The error is thrown because when _handleMessage method is called, the compiler fails to find getIt.registerSingleton<NotificationCubit>(NotificationCubit()); which registers NotificationCubit> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM