Flutter中Pusher Beams getInitialMessage()返回null问题求助
问题排查与解决方案
针对你遇到的getInitialMessage()返回null的问题,可从以下几个方向逐一排查:
1. 检查通知发送的Payload格式
getInitialMessage()只能读取通知**fcm.data字段**中的自定义数据,如果你把参数放在notification字段下,就会获取不到。发送通知的Payload必须符合如下结构:
{ "interests": ["debug-chat"], "fcm": { "data": { "open_magic": "你的Deep Link值" }, "notification": { "title": "测试通知", "body": "点击打开Deep Link" } } }
确保自定义参数open_magic被放在fcm.data层级下,而非notification内。
2. 区分冷启动与热启动场景
getInitialMessage()仅在App完全关闭后点击通知冷启动时有效;- 如果App处于后台,点击通知唤醒属于热启动,此时需要通过
onMessageOpenedApp监听回调获取数据。
修改你的初始化代码,同时处理两种场景:
void init(bool isWeb) async { if (!isWeb) { await PusherBeams.instance.start(instanceID); await PusherBeams.instance.setDeviceInterests(['debug-chat']); // 处理热启动时的通知点击 PusherBeams.instance.onMessageOpenedApp.listen((message) { Logger().d('onMessageOpenedApp: ${message['open_magic'].toString()}'); }); await _initialMessage(); } }
3. 调整getInitialMessage()的调用时机
当前在main函数中直接调用_initialMessage(),可能存在Pusher Beams未完成初始化、消息未加载完成的情况。建议将调用时机延后到App首页的initState中:
class HomePage extends StatefulWidget { const HomePage({super.key}); @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { @override void initState() { super.initState(); _checkInitialMessage(); } Future<void> _checkInitialMessage() async { final initMessage = await PusherBeams.instance.getInitialMessage(); if (initMessage != null) { Logger().d('_initialMessage: ${initMessage['open_magic'].toString()}'); } } }
4. 检查Android端配置是否完整
确认Beams Receiver已注册
在AndroidManifest.xml中确保存在如下配置:
<receiver android:name="com.pusher.pushnotifications.flutter.PushNotificationReceiver" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </receiver>
处理Activity的启动模式
如果你的MainActivity启动模式是singleTop/singleTask,需要在MainActivity中重写onNewIntent方法,确保Pusher Beams能接收通知数据:
// MainActivity.kt override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) PushNotificationsPlugin.onNewIntent(intent) }
内容的提问来源于stack exchange,提问作者Eugene Myname
相关产品推荐
相关产品推荐

