在Flutter中打开推送通知时使用Navigator

3
我使用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.

这意味着我无法访问导航器。有没有办法解决这个问题,从而在用户点击通知时打开特定页面?

1
使用navigatorKey。将其提供给MaterialApp,然后在导航中使用相同的键。因此,您需要在可以随时访问的某个地方定义该键。 - Pokaboom
2个回答

2

将这行代码放在启动屏幕或任何其他起始屏幕的构建中。

FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage);


只有这一行 FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage); 和 _handleMessage 函数。 - Anas Nadeem
我已经在做了,我的问题是_handleMessage函数运行时会抱怨缺少导航器。 - Fabrizio
你能发送你的 main.dart 完整代码吗? - Anas Nadeem
这个应用程序现在有点复杂,我会尽力在问题中添加任何相关部分。 - Fabrizio
好的,只需从 main.dart 中复制粘贴您应用程序的 MaterialApp 小部件即可。 - Anas Nadeem
让我们在聊天中继续这个讨论 - Fabrizio

0

我曾经遇到过同样的问题,情况也一样(从推送通知中启动视图),并通过将MaterialApp作为我的应用程序小部件树的根而不是我的自定义小部件来解决它(如this answer和其他人所述):

void main() {
 runApp(MaterialApp(
   title: 'Navigation Basics',
   home: MyApp(),
 ));
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接