小编ala*_*yak的帖子

当应用程序处于后台/终止状态并且收到 FCM 通知时,如何在 Flutter 中显示本地通知?

我正在尝试在我的 Flutter 应用程序中使用 Firebase Cloud Messaging 实现推送通知服务。这就是 FCM 文档所说的我们应该根据应用程序的当前状态(前台、后台或终止)处理通知的方式:

Foreground:我们有一个onMessage可以监听的流,但 FCM在前台状态时不会显示任何通知,因此我们必须使用FlutterLocalNotificationsPlugin它,这是我的实现:

FirebaseMessaging.onMessage.listen((RemoteMessage remoteMessage) {
      // calling flutter local notifications plugin for showing local notification
      scheduleNotification(remoteMessage);
    });
Run Code Online (Sandbox Code Playgroud)

scheduleNotification方法中我调用该FlutterLocalNotificationsPlugin().show()方法,到目前为止一切都按预期工作

问题从这里开始:

后台,终止:Firebase 在此状态下自动显示通知,并且它有一个onBackgroundMessage。方法,我们可以向该方法传递一个在FCM 显示通知运行的BackgroundMessageHandler 。这是我的后台处理程序的实现:

Future<void> backgroundMessageHandler(
    RemoteMessage remoteMessage) async {
  RemoteNotification? remoteNotification = remoteMessage.notification;
  if (remoteNotification != null) {
    FlutterLocalNotificationsPlugin().show(
        remoteMessage.messageId.hashCode,
        remoteNotification.title,
        remoteNotification.body,
        NotificationDetails(
          android: AndroidNotificationDetails(
              _androidNotificationChannel.id,
              _androidNotificationChannel.name,
              _androidNotificationChannel.description,
              icon: 'launch_background',
              importance: …
Run Code Online (Sandbox Code Playgroud)

mobile push-notification firebase flutter firebase-cloud-messaging

6
推荐指数
1
解决办法
7648
查看次数