You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter iOS端FCM前台通知接收失效,需触发自定义弹窗

Flutter iOS端FCM前台通知接收失效的解决方案

问题根源

你写的FirebaseMessaging.onMessage监听逻辑里,if (notification != null && android != null)这个判断条件在iOS设备上永远不成立——因为iOS的RemoteMessage里根本没有android字段,message.notification!.android始终是null,导致后续调用PushNotificationSystem.readUserRideRequestInformation的代码完全不会执行。

代码修复方案

把判断条件里的android != null去掉,或者根据平台做区分处理,下面是适配iOS的修改后的代码:

/// 应用前台收到通知时触发
FirebaseMessaging.onMessage.listen((RemoteMessage? message) {
  if (message == null) return;
  
  notificationData = message.data;
  RemoteNotification? notification = message.notification;

  // 去掉Android专属判断,让iOS也能进入逻辑分支
  if (notification != null) {
    final rideRequestId = message.data['rideRequestId'];
    // 增加空值判断,避免空指针异常
    if (rideRequestId != null && navigatorKey.currentState?.context != null) {
      PushNotificationSystem.readUserRideRequestInformation(
        rideRequestId, 
        navigatorKey.currentState!.context
      );
    }
  }
});

额外iOS配置检查

除了代码修改,还要确保iOS端的FCM基础配置到位:

  • 确认已在Apple Developer后台生成并配置好APNs证书,且已上传到Firebase控制台的项目设置里。
  • 应用启动时要主动请求推送权限,示例代码:
    await FirebaseMessaging.instance.requestPermission(
      alert: true,
      badge: true,
      sound: true,
    );
    
  • 发送端的通知格式可以添加content_available: true字段,提升iOS前台接收通知的可靠性:
    Map officialNotificationFormat =
    {
      "to": deviceRegistrationToken,
      "notification": bodyNotification,
      "priority": "high",
      "data": dataMap,
      "content_available": true, // 适配iOS前台通知
    };
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 20:33:15