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

Flutter中Firebase通知:前台本地通知点击不触发onMessageOpenedApp

解决前台本地通知点击后的导航问题

当应用处于前台时,你通过flutterLocalNotificationsPlugin显示的是本地通知,而非Firebase推送的系统通知,因此FirebaseMessaging.onMessageOpenedApp监听不到这类通知的点击事件。要处理这种场景的导航,需要利用flutter_local_notifications自带的通知点击回调机制,具体步骤如下:

1. 初始化时配置通知点击回调

在初始化flutterLocalNotificationsPlugin时,设置onSelectNotification回调,用于接收通知点击事件并处理导航:

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

void _initLocalNotifications() async {
  const AndroidInitializationSettings androidInitSettings =
      AndroidInitializationSettings('@mipmap/ic_launcher');
  final InitializationSettings initSettings =
      InitializationSettings(android: androidInitSettings);

  await flutterLocalNotificationsPlugin.initialize(
    initSettings,
    // 通知点击回调
    onSelectNotification: (String? payload) async {
      if (payload != null) {
        // 将payload解析为RemoteMessage对象
        final RemoteMessage message = RemoteMessage.fromMap(jsonDecode(payload));
        // 调用统一的导航处理方法
        handleNavigationToScreen(message);
      }
    },
  );
}

2. 显示通知时传入消息数据作为payload

在调用flutterLocalNotificationsPlugin.show时,将RemoteMessage转为JSON字符串作为payload传入,这样点击通知时就能拿到原始消息数据:

void showFlutterNotification(RemoteMessage message) async {
  // 将RemoteMessage转为JSON字符串
  final String payload = jsonEncode(message.toMap());

  await flutterLocalNotificationsPlugin.show(
    message.notification.hashCode,
    message.notification?.title,
    message.notification?.body,
    NotificationDetails(
      android: AndroidNotificationDetails(
        channel.id,
        channel.name,
        channelDescription: channel.description,
        styleInformation: bigPictureStyleInformation,
        icon: '@mipmap/ic_launcher',
      ),
    ),
    payload: payload, // 传入消息数据
  );
}

3. 统一导航逻辑

保持handleNavigationToScreen方法不变,这样无论应用处于后台、杀死状态还是前台,点击通知后都会执行相同的导航逻辑,确保行为一致性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 14:50:04