I have setup firebase push notifications and notifications are receiving in my flutter app. this is how I have handled it.
Future<void> init() async {
if (Platform.isIOS) {
iosInit();
} else {
await androidInit();
}
getInitialMsg();
//when app in background
FirebaseMessaging.onMessageOpenedApp.listen((msg) {
handleRoutingOnNotificationTap(msg.data);
});
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
showNotification(message);
});
}
I call this init() before runApp().
I use flutter_local_notifications plugin to show notifications in foreground. Because by default it doesn't show notification when notification received when app is in foreground. In background system show notification by default. I don't manually show.
void showNotification(RemoteMessage msg) {
RemoteNotification? notification = msg.notification;
if (notification == null) return;
FlutterLocalNotificationsPlugin().show(
...,
payload: msg.data.toString(),
);
}
I receive notifications in both background and foreground. I want to implement some navigation logic using notification data payload. In current implementation this only works when app is launched from tapping on a notification(which launches the app) when app is in background. I can use this listener for that >
FirebaseMessaging.onMessageOpenedApp.listen((msg) {
handleRoutingOnNotificationTap(msg.data);
});
there's no listener for when notification tapped when app is running?
So in summary what I want to implement is when notification recieving when app is running(foreground) and user taps it > should handle some navigation logic. How do I implement this?
Found the answer. We can use onDidReceiveNotificationResponse of flutterLocalNotificationsPlugin. we can pass a payload string(jsonencoded) in show(...,payload: jsonEncode(msg.data))
to show notificaton(and pass payload) and we can handle this payload in onDidReceiveNotificationResponse callback.
`flutterLocalNotificationsPlugin.initialize(initializationSettings,
onDidReceiveNotificationResponse: onDidReceiveNotificationResponse);`