我正在构建一个使用 FCM 接收推送通知的应用。
我想在点击通知时转到特定屏幕(例如,用户的个人资料)。
在 Android 上,当应用程序刚刚关闭(而不是“被杀死”)时,它工作得很好,但是当应用程序被终止(“被杀死”)时,它就不能工作了。 在 iOS 上,它根本不起作用。
我正在实现它:
通知处理程序:
class NotificationsHandler {
static final NotificationsHandler instance = NotificationsHandler();
final _fcm = FirebaseMessaging();
void onBackgroundNotificationRecevied({Function onReceived}) {
_fcm.configure(
onResume: (message) => onReceived(message),
onLaunch: (message) => onReceived(message),
);
}
}
myMainScreen 的初始化状态:
@override
void initState() {
NotificationsHandler.instance.onBackgroundNotificationRecevied(
onReceived: (message) async {
final userId = message['data']['userId'];
final user = this.users.firstWhere((currentUser) => currentUser.id == userId);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => UserProfileScreen(
user,
),
),
);
}
);
super.initState();
}
发送通知的代码(通过外部 React 管理面板):
const payload = {
notification: {
title: `myTitle`,
body: `My message`,
sound: "default",
badge: "1",
click_action: "FLUTTER_NOTIFICATION_CLICK",
},
data: {
click_action: 'FLUTTER_NOTIFICATION_CLICK',
userId: myUserId,
},
};
const options = {
priority: 'high',
timeToLive: 60 * 60 * 24
};
admin.messaging().sendToTopic('myTopic', payload, options);
有谁知道为什么它不起作用?
谢谢!
最佳答案
您可以尝试使用 getInitialMessage
而不是 onLaunch
。我相信这会做你想做的 documentation指示以下几行:
This should be used to determine whether specific notification interaction should open the app with a specific purpose (e.g. opening a chat message, specific screen etc).
@override
void initState() {
super.initState();
FirebaseMessaging.instance.getInitialMessage().then((RemoteMessage message) {
if (message != null) {
Navigator.pushNamed(context, '/message', arguments: MessageArguments(message, true));
}
});
}
关于firebase - Flutter - onLaunch 中的 Firebase 云消息传递导航不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66506468/