I want to switch to a screen when an FCM background message receives. But for this context
is required which I definitely don't have inside FirebaseBackgroundMessageHandler
so after searching on the internet and I found that I can get the current context from the NavigatorKey
so I created this global variable:
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
and this on my material app:
runApp(GetMaterialApp(
navigatorKey: navigatorKey,
home: const MyHomePage(),));
Now, whenever I receive a background message I try to switch to the desired screen but I always get the null context so couldn't Push
. Navigating through GetX
also throws an error.
What am I missing? Please help!!!!
Firebase background handler:
Future<dynamic> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp();
if(message.data['test'] == '123'){
Navigator.of(navigatorKey.currentContext!).push(MaterialPageRoute(builder: (context) =>const Wallet()));
}
}
According to the documentation of Firebase background messages:
Since the handler runs in its own isolate outside your applications context, it is not possible to update application state or execute any UI impacting logic. You can however perform logic such as HTTP requests, IO operations (updating local storage), communicate with other plugins etc.
So if your application is in the background, you can't initiate the navigation the way you would like. If you present the user with a notification, the user can decide to click it, and then you can use FirebaseMessaging.onMessageOpenedApp
. In this handler you will be able to handle navigation.