Flutter中的Fcm背景通知

时间:2020-05-12 12:24:20

标签: firebase flutter dart firebase-cloud-messaging

我已经在后台使用Firebase消息传递实现了通知。但是,问题是这样的;如何将数据从功能myBackgroundMessageHandler返回到FirebaseNotification?

Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) {
      return Future<void>.value();
    }

    class FirebaseNotifications {
      FirebaseMessaging _firebaseMessaging;
      FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;

      void setUpFirebase() {
        _firebaseMessaging = FirebaseMessaging();
      }

      void fcmListeners() {
        _firebaseMessaging.configure(
          onMessage: (Map<String, dynamic> message) async {
            print("OnMessage");
            processNotification(message);
            return;
          },
          onBackgroundMessage: myBackgroundMessageHandler,
          onLaunch: (Map<String, dynamic> message) async {
            print("onLaunch");
            processNotification(message);
            return;
          },
          onResume: (Map<String, dynamic> message) async {
            print("onResume");
            processNotification(message);
            return;
          },
        );
      }

      processNotification(message) {}
    }

3 个答案:

答案 0 :(得分:0)

当前fireflutter库中存在一个错误。即使您使用了静态或全局变量,也无法从代码中访问变量。

在这里看看:

https://github.com/FirebaseExtended/flutterfire/issues/1878

答案 1 :(得分:0)

我编写了一个小程序,当您的应用程序处于后台或已终止时,它可以允许监听后台消息推送通知。(仅由于我没有iOS帐户,因此在Android上进行了测试)。 >

这是到存储库的链接 点击here

答案 2 :(得分:0)

您必须使用 sharedPreference 来保存来自通知的任何数据并在应用程序中访问它。 由于该函数在其自己的隔离上运行,因此将无法访问应用程序中的任何静态或全局变量。 这是一个演示:

Future<void> firebaseMessagingBackgroundHandler(
  RemoteMessage remoteMessage,
    ) async {
      String logicFlow = remoteMessage.data['logic_flow'];
      if (logicFlow != null) {
      if (logicFlow.isNotEmpty) {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('required_string', logicFlow);
    }
  }
}

此后:您可以使用用于存储 .i.e. 的相同密钥从应用内的任何位置访问该字符串

final prefs = await SharedPreferences.getInstance();
String requiredString  = await prefs.getString('required_string');