首页 > 解决方案 > 锁定屏幕上的 FCM 通知 Flutter

问题描述

我开发了一个应用程序,当手机被锁定时我无法接收 FCM 通知。

_fcm.configure(
  onMessage: (Map<String, dynamic> message) async {
    print("onMessage: $message");
    AwesomeNotifications().createNotification(
        content: NotificationContent(
            id: 100,
            channelKey: "basic_channel",
            title: message['notification']['title'],
            body: message['notification']['body'],
            showWhen: true,
            autoCancel: true));
  },
  onLaunch: (Map<String, dynamic> message) async {
    print("onLaunch: $message");
  },
  onResume: (Map<String, dynamic> message) async {
    print("onResume: $message");
  },
);

我使用了 firebase 和 Awesome Notification 插件来显示通知。

使用的包:firebase_messaging:^7.0.3

下面是我如何显示的代码

   class _MyAppState extends State<MyApp> {
  @override
    Widget build(BuildContext context) {
      final pushNotificationService = PushNotificationService(_firebaseMessaging);
      pushNotificationService.initialise();
  }
}

谁能帮帮我,我卡在这里谢谢

标签: androidflutterpush-notificationfirebase-cloud-messaging

解决方案


我可以建议你改变功能,你可以实现这样的东西:

void subscribeChannel(String data) async =>
    await FirebaseMessaging.instance.subscribeToTopic(data);

void unsubscribeChannel(String channelId) async =>
    await FirebaseMessaging.instance.unsubscribeFromTopic(channelId);

void listenNotificationEvents() {
  FirebaseMessaging.instance.getInitialMessage().then(
    (value) async {
      if (value != null) setLocalNotification(value);
    },
  );
  FirebaseMessaging.onMessage.listen((event) {
    if (event.data.isNotEmpty) setLocalNotification(event);
  });
  FirebaseMessaging.onMessageOpenedApp.listen((event) {
    if (event.data.isNotEmpty) changeScreen(event.data);
  });
}

这些功能基本上是让 firebase 设置所有内容并启用即使应用程序已被杀死或在后台也能接收通知。

在您的MaterialApp 上,您需要使用它。

FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
try {
  FirebaseMessaging.onBackgroundMessage(
      (message) => onBackgroundMessage(message.data));
} catch (_) {}

最后,如果您收到通知,并且应用程序已打开,firebase 将执行块代码中的所有内容,因此最后的更改是在 onMessage 中设置本地通知的设置。

如果这对您有帮助,请告诉我。


推荐阅读