Flutter Firebase中如何在getInitialMessage获取自定义Payload数据
解决方案
1. 修正Firebase推送消息的Payload结构
自定义的screen和url字段必须放在data节点下,而非notification节点内。Firebase的data字段会完整传递消息数据到RemoteMessage,这是getInitialMessage()能读取到自定义字段的关键。
Postman中发送的正确JSON示例:
{ "to": "YOUR_DEVICE_TOKEN", "data": { "screen": "product_detail", "url": "https://your-domain.com/product/123", "title": "新品上架", "body": "点击查看详情" }, "notification": { "title": "新品上架", "body": "点击查看详情" } }
2. 正确调用getInitialMessage()并解析数据
确保在App初始化阶段调用该方法,且从RemoteMessage.data中提取自定义字段:
void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); // 处理冷启动时的通知点击 RemoteMessage? initialMessage = await FirebaseMessaging.instance.getInitialMessage(); if (initialMessage != null) { final String? targetScreen = initialMessage.data['screen']; final String? targetUrl = initialMessage.data['url']; if (targetScreen != null && targetUrl != null) { // 执行页面跳转或业务逻辑,比如导航到指定页面 // Navigator.pushNamed(context, targetScreen, arguments: targetUrl); } } runApp(const MyApp()); }
3. 区分冷启动与后台唤醒场景
getInitialMessage()仅适用于冷启动(App完全关闭后通过通知打开),如果是App在后台时点击通知唤醒,需要用onMessageOpenedApp监听:
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) { final String? targetScreen = message.data['screen']; final String? targetUrl = message.data['url']; // 处理后台唤醒后的页面跳转逻辑 });
4. 排查Awesome Notifications的干扰
确保Awesome Notifications的配置不会拦截Firebase的原始消息传递。如果Awesome Notifications接管了通知展示,需确认它是否完整保留了data字段的内容,避免在处理过程中丢失自定义参数。
内容的提问来源于stack exchange,提问作者Man Steel
相关产品推荐
相关产品推荐

