【问题标题】:Use Navigator upon push notification opening in Flutter在 Flutter 中打开推送通知时使用 Navigator
【发布时间】:2021-10-15 15:33:51
【问题描述】:

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

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

【问题讨论】:

  • 使用导航键。将其交给 materialApp,然后使用相同的键进行导航。所以你需要在某个地方定义那个键,你可以在任何你想要的地方访问它

标签: firebase flutter push-notification


【解决方案1】:

将这一行移到您的初始屏幕或任何其他起始屏幕构建处。

FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage);

【讨论】:

  • 只有这一行 FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage);和 _handleMessage 函数
  • 我已经在做,我的问题是函数 _handleMessage 运行但它抱怨缺少导航器。
  • 你能把你的main.dart完整代码发过来吗
  • 该应用程序现在有点复杂,我会尽力将任何相关部分添加到问题中。
  • 好的,只需从 main.dart 复制粘贴您应用的 MaterialApp 小部件
猜你喜欢
  • 2016-12-11
  • 2020-02-14
  • 1970-01-01
  • 1970-01-01
  • 2020-12-31
  • 2020-05-13
  • 2019-06-15
  • 1970-01-01
  • 2020-11-04
相关资源
最近更新 更多