Android已终止状态下FirebaseMessaging.getInitialMessage()始终返回null
Android端Awesome Notification终止状态点击跳转问题解决
你遇到的核心问题是:虽然用Awesome Notification接收推送,但错误地依赖Firebase Messaging的getInitialMessage()来获取终止状态下的通知点击事件——Android端推送由Awesome Notification接管后,Firebase无法捕获到初始消息,导致remoteMessage始终为null。
以下是针对性的解决方案:
1. 改用Awesome Notification的初始化回调处理终止状态点击
在初始化Awesome Notification时,通过initialCallback参数处理应用从终止状态被通知唤起的场景:
void main() async { WidgetsFlutterBinding.ensureInitialized(); // 初始化Awesome Notification await AwesomeNotifications().initialize( 'resource://drawable/res_app_icon', // 替换为你的通知图标路径 [ NotificationChannel( channelKey: 'basic_channel', channelName: '基础通知渠道', channelDescription: '用于常规通知的渠道', defaultColor: const Color(0xFF9D50DD), ledColor: Colors.white, ) ], // 关键:处理终止状态下的通知点击 initialCallback: (receivedNotification) { if (receivedNotification.payload != null) { // 从payload中提取跳转参数 final catId = receivedNotification.payload!['category_id']; final showMain = receivedNotification.payload!['showMain']; final offer = receivedNotification.payload!['offer']; // 等待Widget树初始化完成后执行跳转 WidgetsBinding.instance.addPostFrameCallback((_) { if (navigatorKey.currentContext != null) { Navigator.push( navigatorKey.currentContext!, MaterialPageRoute( builder: (context) => DashboardPage( catId: catId, showMain: showMain, offer: offer, ), ), ); } }); } }, ); runApp(const MyApp()); }
2. 确保推送参数正确传递到Awesome Notification的Payload
在接收Firebase远程消息时,要将消息中的data参数传递给Awesome Notification的payload,这样终止状态点击时才能拿到跳转参数:
void setupFirebaseMessaging() async { // 前台接收消息,用Awesome Notification展示 FirebaseMessaging.onMessage.listen((RemoteMessage message) { AwesomeNotifications().createNotification( content: NotificationContent( id: DateTime.now().millisecondsSinceEpoch, channelKey: 'basic_channel', title: message.notification?.title ?? '', body: message.notification?.body ?? '', ), payload: message.data, // 把Firebase的data数据传递给通知payload ); }); // 后台状态下的通知点击处理(保留原有逻辑即可) FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) { if (navigatorKey.currentContext != null) { Navigator.push( navigatorKey.currentContext!, MaterialPageRoute( builder: (context) => DashboardPage( catId: message.data['category_id'], showMain: message.data['showMain'], offer: message.data['offer'], ), ), ); } }); // 移除原有的getInitialMessage逻辑,改用Awesome Notification的initialCallback }
3. 额外检查项
- 确保Awesome Notification使用最新版本,避免已知bug;
- 检查AndroidManifest.xml中Activity的launchMode,建议使用默认的
standard,避免路由上下文异常; - 测试时完全杀死应用进程(不要仅按Home键),再点击通知验证跳转逻辑。
内容的提问来源于stack exchange,提问作者user29108148
相关产品推荐
相关产品推荐

