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

Flutter FCM前台通知移入DDD分层后失效的修复方案

前台FCM onMessage事件不触发的修复方案

1. 修正DI初始化时机

确保FirebasePushNotificationService的初始化逻辑在应用启动最早期执行,而非依赖UI页面的加载。前台消息监听需要在应用启动阶段就完成注册,否则会错过前台状态下的消息推送。

示例代码:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  // 初始化DI容器
  await initDependencyInjection();
  // 立即获取推送服务实例并启动监听
  final pushService = getIt<PushNotificationService>();
  await pushService.initNotificationListeners();
  runApp(const MyApp());
}

2. 确保onMessage监听直接注册在服务层

在FirebasePushNotificationService的初始化方法中直接绑定FirebaseMessaging.onMessage监听,不要将监听逻辑分散到UI层。

示例代码:

class FirebasePushNotificationService implements PushNotificationService {
  final NotificationHandler _notificationHandler;

  FirebasePushNotificationService(this._notificationHandler);

  @override
  Future<void> initNotificationListeners() async {
    // 前台消息监听注册
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      _notificationHandler.displayForegroundNotification(message);
    });
    // 后台/终止状态消息处理逻辑保持不变
    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      _notificationHandler.handleNotificationTap(message);
    });
  }
}

3. 检查平台配置完整性

  • Android:在AndroidManifest.xml中配置有效通知渠道,并且在服务初始化时创建渠道:
    Future<void> _createAndroidNotificationChannel() async {
      const channel = AndroidNotificationChannel(
        'foreground_channel',
        '前台通知渠道',
        description: '用于展示应用前台收到的推送通知',
        importance: Importance.high,
      );
      final notificationManager = NotificationManagerCompat.from(WidgetsBinding.instance.context);
      await notificationManager.createNotificationChannel(channel);
    }
    
  • iOS:在Info.plist中添加UIBackgroundModes并包含remote-notification,同时在服务初始化时请求通知权限:
    await FirebaseMessaging.instance.requestPermission(
      alert: true,
      badge: true,
      sound: true,
    );
    

4. 验证DI注册的单例模式

确保FirebasePushNotificationService在DI容器中注册为单例,避免多次创建实例导致监听被覆盖或未正确生效。

示例(以get_it为例):

getIt.registerSingleton<PushNotificationService>(
  FirebasePushNotificationService(getIt<NotificationHandler>()),
);

5. 排查监听被意外取消的情况

在onMessage.listen回调中添加日志输出,确认监听是否被正确注册且未被其他逻辑取消:

FirebaseMessaging.onMessage.listen((RemoteMessage message) {
  print('[FCM前台消息] 收到推送: ${message.notification?.title}');
  _notificationHandler.displayForegroundNotification(message);
});

内容的提问来源于stack exchange,提问作者Atlas-Pio

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 19:22:13