簡體   English   中英

onMessage:對傳入消息調用兩次回調 Flutter web

[英]onMessage: callback called twice on incoming messages Flutter web

在我的應用程序中,對於 web 版本,我將包firebase 7.3.0用於 Firebase 服務,我現在也在為 web 設置 FCM。 當我在前台收到應用程序的新消息時, onMessage: from messaging()被觸發兩次。 在某個 Flutter 版本之前,它也曾經發生在flutter_messaging設備插件上,但現在已經解決了。

我基本上設置了一個StreamTransformer以獲取與PlatformPushNotificationDevice使用的flutter_messaging設備包相同類型的Map<String, dynamic>中的flutter_messaging ,我使用 Stub 根據平台切換類。 在 Web 類PlatformPushNotificationWeb我將消息實例化為var firebaseMessaging = messaging(); 並聲明我的方法,其中之一是onMessage()

Stream<Map<String, dynamic>> onMessage()  async* {

    print('PlatformPushNotificationWeb.onMessage() started');
    handleData(Payload payload, EventSink<Map<String, dynamic>> sink) {
        Map<String,dynamic> message = {
          'notification': {
            'title': payload.notification.title,
            'body': payload.notification.body,
            'sound': true
          },
          'data': payload.data
        };
      sink.add(message);
    }

    final transformer = StreamTransformer<Payload, Map<String, dynamic>>.fromHandlers(
        handleData: handleData);

    yield* firebaseMessaging.onMessage.transform(transformer);
  }

因此無論平台如何,我的集團中的偵聽器都會收到相同的消息類型,

Stream<PushNotificationState> _mapListenToMessagesToState(ListenToMessages event) async* {
    print('_mapListenToMessagesToState started');
    _pushNotificationSwitcher.onMessage().listen((message) {
      print('_mapListenToMessagesToState onMessage() listener: received new message');
      add(ReceivedNewMessage(message: message));
    });
  }

但是對於每條傳入消息,我都會讓聽眾響應兩次。

我將index.html設置為:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>fixit cloud biking</title>
  <!--  <meta name="google-signin-client_id" content="YOUR_GOOGLE_SIGN_IN_OAUTH_CLIENT_ID.apps.googleusercontent.com">-->
  <meta name="google-signin-client_id" content="xxxx.apps.googleusercontent.com">
<!--  <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">-->
</head>
<!--<body>-->
<body id="app-container">
<script src="main.dart.js?version=45" type="application/javascript"></script>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.19.1/firebase-app.js"></script>

<!-- TODO: Add SDKs for Firebase products that you want to use
     https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/7.19.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.19.1/firebase-analytics.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.19.1/firebase-messaging.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.19.1/firebase-storage.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.19.1/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.19.1/firebase-remote-config.js"></script>


<script>
if ("serviceWorker" in navigator) {
  window.addEventListener("load", function () {
     //navigator.serviceWorker.register("/flutter_service_worker.js");
    navigator.serviceWorker.register("/firebase-messaging-sw.js");
  });
}
</body>
</html>

firebase-messaging-sw.js文件為:

importScripts("https://www.gstatic.com/firebasejs/7.19.1/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/7.19.1/firebase-messaging.js");

firebase.initializeApp({
  apiKey: "xxxx",
            authDomain: "xxxx",
            databaseURL: "xxxx",
            projectId: "xxx",
            storageBucket: "xxxx",
            messagingSenderId: "xxxx",
            appId: "xxx",
            measurementId: "G-xxxx",
});
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);

    const promiseChain = clients
        .matchAll({
            type: "window",
            includeUncontrolled: true
        })
        .then(windowClients => {
            for (let i = 0; i < windowClients.length; i++) {
                const windowClient = windowClients[i];
                windowClient.postMessage(payload);
            }
        })
        .then(() => {
            return registration.showNotification("New Message");
        });
    return promiseChain;
});
self.addEventListener('notificationclick', function (event) {
    console.log('notification received: ', event)
});

難道是在PlatformPushNotificationWeb類和firebase-messaging-sw.js文件中實例化消息firebase-messaging-sw.js的原因是onMessage:回調被觸發兩次? 非常感謝。

事實證明......一個很好的顫振清潔,Android Studio 和機器重啟解決了它..

現在我沒有收到兩次相同的消息,但是對於那些實際上正在嘗試重復消息的人來說,這將解決它,這只是一種解決方法。

剛剛聲明了int lastMessageId = 0變量。 當一條消息進來時,根據它檢查它的id ,只有當它們不同時,才將新消息 id 保存為lastMessageId並顯示消息。

Stream<PushNotificationState> _mapListenToMessagesToState(ListenToMessages event) async* {
    print('_mapListenToMessagesToState started');
    int lastMessageId = 0;

    _pushNotificationSwitcher.onMessage().listen((message) {
      print('incoming message is : $message');
      var data = message['data'];
      int messageId = int.parse(data['id']);

      if( lastMessageId != messageId) {
        lastMessageId = messageId;
        print(
            '_mapListenToMessagesToState onMessage() listener: received new message');
        add(ReceivedNewMessage(message: message));
      }
    });
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM