navigatorKey.currentContext 始终为空

navigatorKey.currentContext is Always Null

我想在收到 FCM 后台消息时切换到屏幕。但是为此 context 是必需的,我的 Firebase 后台消息处理程序中绝对没有,所以我在互联网上搜索,发现我可以从 navigator key 获取上下文,所以我创建了这个全局变量:

final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

这在我的 material 应用程序上:

runApp(GetMaterialApp(
    navigatorKey: navigatorKey,
    home: const MyHomePage(),));

现在,每当我收到背景消息时,我都会尝试切换到所需的屏幕,但我总是得到空上下文,所以不能 Push。浏览 GetX 也会抛出错误。 我错过了什么?请帮忙!!!!

myFB 后台处理程序:

Future<dynamic> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  if(message.data['test'] == '123'){
    Navigator.of(navigatorKey.currentContext!).push(MaterialPageRoute(builder: (context) =>const Wallet()));
  }
}

根据Firebase后台消息documentation

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.

因此,如果您的应用程序在后台运行,您将无法以您希望的方式启动导航。如果你给用户一个通知,用户可以决定点击它,然后你就可以使用FirebaseMessaging.onMessageOpenedApp。在此处理程序中,您将能够处理导航。