在 Flutter 中打开推送通知时使用导航器

问题描述 投票:0回答:2
我正在使用 Firebase Cloud Messaging 通过云功能向我的 flutter 应用程序发送推送通知,并在通知中添加数据,这些数据将定义用户点击通知时将打开的页面。

这是我用来处理修改的逻辑:

void _handleMessage(RemoteMessage message) { Navigator.pushNamed(context, "/shop", arguments: message.data["id"]); return; } Future<void> setupInteractedMessage() async { // Get any messages which caused the application to open from // a terminated state. RemoteMessage? initialMessage = await FirebaseMessaging.instance.getInitialMessage(); // If the message also contains a data property with a "type" of "chat", // navigate to a chat screen if (initialMessage != null) { _handleMessage(initialMessage); } // Also handle any interaction when the app is in the background via a // Stream listener FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage); }
初始化 firebase 应用程序时,我正在调用 

setupInteractedMessage();

这可行,但是当应用程序位于后台并且我点击通知时,我收到以下错误:

[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Navigator operation requested with a context that does not include a Navigator. The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.
这意味着我无法访问导航器。有没有办法解决这个问题,从而在用户点击通知时打开特定页面?

firebase flutter push-notification
2个回答
3
投票
将此行移至启动屏幕或任何其他启动屏幕构建处。

FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage);
    

0
投票
我在相同的场景中遇到了同样的问题(从推送通知启动视图),并通过将

MaterialApp

 作为我的应用程序小部件树的根而不是我自己的小部件来解决它(根据
这个答案和其他人):

void main() { runApp(MaterialApp( title: 'Navigation Basics', home: MyApp(), )); }
    
© www.soinside.com 2019 - 2024. All rights reserved.