Flutter Web 推送通知与 firebase

问题描述 投票:0回答:1

我配置了 Flutter 来接收推送通知,但我找不到 Web 平台的方法。 所有的文章和教程都有点旧了,我认为它们没什么用。

我使用 flutterfire 命令来配置 Firebase,它非常适合 Android。

flutter web push-notification firebase-cloud-messaging
1个回答
0
投票

首先将 firebase_core 和 firebase_messaging 添加到您的 pubspec.yaml

在 main() 函数中添加 init Firebase

await Firebase.initializeApp(
        options: const FirebaseOptions(
            apiKey: "xxxx",
  authDomain: "xxxxx",
  databaseURL: "xxxx",
  projectId: "xxxxx",
  storageBucket: "xxxx",
  messagingSenderId: "xxxxx",
  appId: "xxxxxx"));

初始化 Firebase 后,您必须初始化 Firebase 消息传递并在浏览器中请求通知,您可以这样做

FirebaseMessaging messaging = FirebaseMessaging.instance;
    messaging.requestPermission(
      alert: true,
      announcement: false,
      badge: true,
      carPlay: false,
      criticalAlert: false,
      provisional: true,
      sound: true,
    );
    NotificationSettings settings = await messaging.getNotificationSettings();

将其添加到 JavaScript 文件中

importScripts('https://www.gstatic.com/firebasejs/10.7.1/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/10.7.1/firebase-messaging-compat.js');

const firebaseConfig = {
  apiKey: "xxxx",
  authDomain: "xxxxx",
  databaseURL: "xxxx",
  projectId: "xxxxx",
  storageBucket: "xxxx",
  messagingSenderId: "xxxxx",
  appId: "xxxxxx"
};

firebase.initializeApp(firebaseConfig);

const messaging = firebase.messaging();

messaging.onBackgroundMessage(function(payload) {
    console.log('Received background message ', payload);

    const notificationTitle = payload.notification.title;
    const notificationOptions = {
        body: payload.notification.body,
      };

    return self.registration.showNotification(notificationTitle, notificationOptions);
});

将其添加到您的index.html文件中

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

那么你基本上就可以开始了,这就是你所要做的。然后转到 https://console.firebase.google.com/u/0/project/your-project-id/messaging 并将您的 flutter web 应用程序添加到其中,并通过获取使用 wait FirebaseMessaging.instance.getToken(); 从您的应用程序获取令牌

© www.soinside.com 2019 - 2024. All rights reserved.