Flutter中FCM推送配置Deep Link适配GoRouter及通知显示问题
FCM推送与GoRouter Deep Link联动方案
一、点击通知处理Deep Link的逻辑
FCM推送分两种场景,处理逻辑略有不同:
- 后台/应用杀死状态:系统会自动展示通知,点击后唤醒应用。此时需在FCM的回调中提取携带的Deep Link,手动调用GoRouter的跳转方法(比如
context.go(deepLink))。 - 前台状态:FCM不会自动弹出通知,需自行监听消息并处理(比如借助flutter_local_notifications展示通知),点击通知时同样提取Deep Link再调用GoRouter跳转。
二、Android & iOS的FCM Payload配置
GoRouter无法自动识别FCM通知中的Deep Link,必须手动提取后跳转,因此只需把Deep Link放在data字段中即可,统一格式方便两端处理:
Android Payload示例
{ "notification": { "title": "新消息", "body": "点击查看详情", "click_action": "FLUTTER_NOTIFICATION_CLICK" // 必须配置,确保点击触发应用内回调 }, "data": { "deep_link": "yourapp://detail/123" // 你的Deep Link地址 }, "to": "设备令牌" }
iOS Payload示例
{ "aps": { "alert": { "title": "新消息", "body": "点击查看详情" }, "content-available": 1 // 可选,用于唤醒后台应用处理消息 }, "data": { "deep_link": "yourapp://detail/123" }, "to": "设备令牌" }
注意:需确保你已完成Android(AndroidManifest.xml配置intent-filter)和iOS(Info.plist配置URL Scheme/Universal Links)的Deep Link基础配置,这部分你已经通过终端测试验证正常,无需额外修改。
三、是否需要flutter_local_notifications包?
- 后台/应用杀死状态:不需要,Android和iOS系统会自动展示FCM通知,点击后唤醒应用。
- 前台状态:必须使用该包展示通知,因为FCM在应用前台时不会自动弹出通知,需监听
onMessage回调,用flutter_local_notifications创建并显示通知。 - 另外,若需自定义通知样式(如大图标、自定义布局、声音、震动),或处理前台通知的点击跳转逻辑,也需要依赖这个包。
核心处理代码示例
// 处理后台/杀死状态下的通知点击 FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) { final deepLink = message.data['deep_link']; if (deepLink != null) { GoRouter.of(context).go(deepLink); } }); // 处理前台消息,用flutter_local_notifications展示通知 FirebaseMessaging.onMessage.listen((RemoteMessage message) { RemoteNotification? notification = message.notification; AndroidNotification? android = message.notification?.android; if (notification != null && android != null) { flutterLocalNotificationsPlugin.show( notification.hashCode, notification.title, notification.body, NotificationDetails( android: AndroidNotificationDetails( channel.id, channel.name, channel.description, icon: android.smallIcon, ), ), payload: message.data['deep_link'], // 传递Deep Link作为通知payload ); } }); // 监听前台通知的点击事件 flutterLocalNotificationsPlugin.initialize( InitializationSettings( android: AndroidInitializationSettings('@mipmap/ic_launcher'), iOS: IOSInitializationSettings(), ), onSelectNotification: (String? payload) async { if (payload != null) { GoRouter.of(context).go(payload); } }, );
内容的提问来源于stack exchange,提问作者DevelJoe
相关产品推荐
相关产品推荐

