You need to enable JavaScript to run this app. Flutter firebase_messaging如何仅清除选中通知?iOS点击通知其余消失问题
优惠活动
大模型
产品
解决方案
定价
更多

Flutter firebase_messaging如何仅清除选中通知?iOS点击通知其余消失问题

适配firebase_messaging ^6.0.13的iOS通知点击单条清除方案

问题根因

iOS端点击单条通知却清空所有通知,是两个逻辑叠加导致的:

  • 旧版firebase_messaging 6.0.13的默认回调内置了全量清理通知栏的逻辑,没有做单条粒度的处理
  • 原生侧如果在通知响应流程里调用了全局清除方法,会直接清空所有已展示的通知,和推送内容本身无关

落地解决步骤

  • 删掉所有全局清除通知的代码
    逐行排查两处逻辑:
    • Flutter侧的通知点击回调(onLaunch、onResume、onMessage)中,是否存在调用FlutterLocalNotificationsPlugin的cancelAll()的代码
    • iOS原生工程AppDelegate中,是否存在调用UNUserNotificationCenter.current().removeAllDeliveredNotifications()的代码
      所有触发全量清除的代码必须全部移除,这是导致通知被批量清空的直接诱因。
  • 实现单条通知的定向移除
    首先要保证每条下发的APNs推送配置唯一的通知标识,不要所有通知共用同一个id,给每条通知的request.identifier设置独立值。
    然后在iOS原生AppDelegate的通知点击代理方法中,只移除当前被点击的单条通知,参考实现:
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        // 仅传入当前被点击通知的唯一id做定向移除,不要调用全量清除方法
        center.removeDeliveredNotifications(withIdentifiers: [response.notification.request.identifier])
        completionHandler()
    }
    
  • 覆盖firebase_messaging的默认回调行为
    firebase_messaging 6.0.13版本默认回调会触发自动全量清理,需要在初始化时显式覆盖该行为:
    FirebaseMessaging.instance.configure(
      onLaunch: (message) async {
        // 仅处理跳转逻辑,不要附带任何通知栏清除操作
        return;
      },
      onResume: (message) async {
        // 同上,只做页面跳转,不操作通知栏
        return;
      },
    );
    

注意细节

如果项目同时集成了flutter_local_notifications,要保证Flutter侧的通知id和原生APNs推送的id做映射对齐,避免点击时无法匹配到对应单条通知的id,最终回退为全量清除逻辑。

内容的提问来源于stack exchange,提问作者Tester12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.11 02:54:03