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

Flutter中点击FCM通知跳转至指定页面的实现方案

实现FCM前台通知点击跳转页面的修改方案

要实现前台收到FCM通知后,点击通知跳转指定页面,需要完成以下3个核心修改:


1. 配置全局导航键

首先定义全局NavigatorState键,确保在通知点击回调中能获取到导航上下文:

// 在全局范围内定义(比如main.dart顶部)
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

然后在MaterialApp中绑定该键:

MaterialApp(
  navigatorKey: navigatorKey, // 绑定全局导航键
  home: const YourHomePage(),
  // 其他配置项...
);

2. 初始化本地通知时添加点击回调

在初始化flutterLocalNotificationsPlugin时,设置onSelectNotification回调处理通知点击事件:

await flutterLocalNotificationsPlugin.initialize(
  InitializationSettings(
    android: AndroidInitializationSettings('drawable/small_launcher_icon'),
    // iOS平台需添加对应初始化配置:iOS: DarwinInitializationSettings()
  ),
  onSelectNotification: (String? payload) async {
    if (payload == null) return;
    
    // 解析传递的通知数据
    final notificationData = jsonDecode(payload);
    
    // 跳转到目标页面,替换为你实际的页面组件
    navigatorKey.currentState?.push(
      MaterialPageRoute(
        builder: (context) => TargetPage(
          version: notificationData['version'],
          size: notificationData['size'],
        ),
      ),
    );
  },
);

3. 显示通知时传递payload参数

修改现有代码中flutterLocalNotificationsPlugin.show的调用,添加payload参数传递跳转所需数据:

flutterLocalNotificationsPlugin.show(
  0, // Notification ID
  remoteMessage.notification?.title ?? 'default title',
  remoteMessage.notification?.body ?? 'default body',
  notificationDetails,
  // 传递跳转数据,转成JSON字符串格式
  payload: jsonEncode({
    'version': version,
    'size': size,
  }),
);

注意事项

  • 确保flutter_local_notifications插件为最新版本,避免API兼容问题
  • 若需区分不同通知跳转不同页面,可在payload中添加targetPage标识字段,在点击回调中做分支处理
  • iOS平台需额外配置通知权限和前台通知展示权限,具体参考插件官方说明

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 13:03:37