You need to enable JavaScript to run this app. Flutter集成FCM与本地通知的前后台异常排查及功能实现
优惠活动
大模型
产品
解决方案
定价
更多

Flutter集成FCM与本地通知的前后台异常排查及功能实现

核心问题梳理
  • 已实现应用被杀死状态下FCM通知正常送达
  • 当前存在三类异常/需求:
    1. 应用处于前台/后台运行时,通知无法正常展示
    2. 调整代码后通知栏展示正常,但onResume回调中的页面跳转逻辑不生效
    3. 目标需求:onMessage(前台收到消息)、onResume(后台点击通知唤起应用)触发时,自动弹出Alert弹窗
  • 观测到的异常日志特征:
    E/FlutterFcmService(14434): Fatal: failed to find callback
    W/FirebaseMessaging(14434): Missing Default Notification Channel metadata in AndroidManifest. Default value will be used.
    W/ConnectionTracker(14434): java.lang.IllegalArgumentException: Service not registered: lu@fb04880
    I/flutter (14434): onResume: {notification: {}, data: {badge: 1, collapse_key: com.HT, google.original_priority: high, google.sent_time: 1607733798, google.delivered_priority: high, sound: default, google.ttl: 2419200, from: 774876, body: Body, title: Title, click_action: FLUTTER_NOTIFICATION_CLICK, google.message_id: 0:1607573733816296%850a56}}
    
    从回调数据可以看到:消息结构中notification字段为空对象,所有通知内容都存储在data字段中,这是早期代码取不到通知内容、执行中断的核心原因。
根因定位
  • 消息取值逻辑不兼容:代码直接读取message['notification']['title']取通知内容,遇到纯data类型的FCM消息时会触发空值异常,导致后续执行流中断
  • 路由上下文引用错误:FCM配置写在MyApp的State中,使用的是MaterialApp外层的局部context,无法获取内部的路由实例,ExtendedNavigator.of(context)调用无效,跳转逻辑自然不生效
  • 插件初始化顺序错误:在onMessage回调里才调用flutterLocalNotificationsPlugin.initialize,导致本地通知插件初始化延迟,部分场景下找不到对应的回调方法,触发failed to find callback错误
  • 跳转时机过早:应用从后台唤起触发onResume时,根Widget还未完成渲染,此时执行路由跳转操作会被渲染流程拦截
修正方案
  • 调整初始化顺序:在Widget初始化阶段完成本地通知插件初始化、通知渠道创建、FCM权限请求、回调绑定,所有初始化逻辑不放在消息回调中执行
  • 消息取值做兼容判断:同时兼容通知消息、纯data消息两种结构,分别从notification和data字段取标题、内容,避免空值异常
  • 解决路由上下文依赖:给全局导航设置navigatorKey,不依赖build方法中的局部context,在任意位置都可以拿到合法的路由实例执行跳转
  • 调整跳转时机:在onResume/onLaunch回调中给路由跳转加200ms左右的延迟,等根Widget完成渲染后再执行跳转操作
  • 抽离公共弹窗逻辑:封装通用的Alert弹窗方法,在onMessage(前台收消息)、onResume(后台点通知唤起)触发时按需调用
  • 补全Android端配置:在AndroidManifest.xml中补上FCM默认通知渠道的meta配置,消除渠道缺失的运行时警告
修正后的核心代码
// 全局路由Key,解决跨组件获取Navigator实例的问题
final globalNavigatorKey = GlobalKey<NavigatorState>();

class _MyAppState extends State<MyApp> {
  final FirebaseMessaging _fcm = FirebaseMessaging();
  final FlutterLocalNotificationsPlugin _localNotif = FlutterLocalNotificationsPlugin();

  @override
  void initState() {
    super.initState();
    _initNotificationModules();
  }

  // 统一初始化所有通知相关模块
  Future<void> _initNotificationModules() async {
    // 本地通知插件初始化
    final androidInitSettings = AndroidInitializationSettings('@mipmap/ic_launcher');
    final iosInitSettings = IOSInitializationSettings(
      onDidReceiveLocalNotification: _showIosLegacyAlert,
    );
    final initSettings = InitializationSettings(
      android: androidInitSettings,
      iOS: iosInitSettings,
    );
    await _localNotif.initialize(
      initSettings,
      onSelectNotification: _onLocalNotificationTapped,
    );

    // 创建Android端通知渠道
    const notificationChannel = AndroidNotificationChannel(
      'my_channel',
      'Channel Name',
      'Channel Description',
      importance: Importance.max,
      enableVibration: true,
    );
    await _localNotif
        .resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(notificationChannel);

    // 请求FCM通知权限
    await _fcm.requestNotificationPermissions();

    // 绑定FCM所有回调
    _fcm.configure(
      // 应用在前台收到消息
      onMessage: (message) async {
        debugPrint('前台收到FCM消息: $message');
        final title = message['notification']?['title'] ?? message['data']['title'];
        final body = message['notification']?['body'] ?? message['data']['body'];

        // 触发Alert弹窗
        _showCommonAlert(title: title, content: body);
        // 通知栏展示本地通知
        await _showNotificationOnBar(title, body);
      },
      // 应用被杀死状态下点击通知冷启动进入
      onLaunch: (message) async {
        debugPrint('冷启动进入应用: $message');
        // 等待路由初始化完成后跳转
        await Future.delayed(const Duration(milliseconds: 200));
        globalNavigatorKey.currentState?.pushNamed(Routes.bookingQRScan);
      },
      // 应用在后台运行时点击通知回到前台
      onResume: (message) async {
        debugPrint('后台唤起应用: $message');
        final title = message['data']['title'];
        final body = message['data']['body'];

        // 触发Alert弹窗
        _showCommonAlert(title: title, content: body);
        // 等待页面渲染完成后跳转
        await Future.delayed(const Duration(milliseconds: 200));
        globalNavigatorKey.currentState?.pushNamed(Routes.bookingQRScan);
      },
    );
  }

  // 公共Alert弹窗方法
  void _showCommonAlert({required String title, required String content}) {
    showDialog(
      context: globalNavigatorKey.currentContext!,
      builder: (context) => AlertDialog(
        title: Text(title),
        content: Text(content),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('确定'),
          )
        ],
      ),
    );
  }

  // iOS 10以下版本的弹窗适配
  Future<void> _showIosLegacyAlert(int id, String? title, String? body, String? payload) async {
    showDialog(
      context: globalNavigatorKey.currentContext!,
      builder: (context) => CupertinoAlertDialog(
        title: Text(title ?? ''),
        content: Text(body ?? ''),
        actions: [
          CupertinoDialogAction(
            child: const Text('确定'),
            onPressed: () => Navigator.pop(context),
          )
        ],
      ),
    );
  }

  // 通知栏展示本地通知
  Future<void> _showNotificationOnBar(String title, String body) async {
    const androidDetails = AndroidNotificationDetails(
      'my_channel',
      'Channel Name',
      'Channel Description',
      importance: Importance.max,
      priority: Priority.high,
    );
    const notifDetails = NotificationDetails(android: androidDetails);
    await _localNotif.show(0, title, body, notifDetails, payload: 'notif_tap');
  }

  // 本地通知点击回调
  Future<void> _onLocalNotificationTapped(String? payload) async {
    if (payload == null) return;
    await Future.delayed(const Duration(milliseconds: 200));
    globalNavigatorKey.currentState?.pushNamed(Routes.bookingQRScan);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorKey: globalNavigatorKey, // 绑定全局路由Key
      theme: ThemeData(primarySwatch: Colors.blue),
      debugShowCheckedModeBanner: false,
      home: const AnimatedSplashScreen(),
      builder: ExtendedNavigator.builder(router: a.Router()),
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.14 09:06:07