I’m working on a Flutter application that utilizes Firebase Cloud Messaging (FCM) for push notifications. My backend is configured to send data messages to the app, and I’m using local notifications to handle them within the app successfully. However, I’m facing an issue when handling taps on these local notifications.
Problem Statement:
- Notification Tap Handling: I’m using the flutter_local_notifications plugin to display local notifications in my Flutter app. How can I handle taps on these notifications
void initialize() {
const InitializationSettings initSettings = InitializationSettings(
android: AndroidInitializationSettings("@mipmap/ic_launcher"),
);
_localNotificationsPlugin.initialize(initSettings,
onDidReceiveBackgroundNotificationResponse: (details) {
// How to handle tap on local notifications here // Can't use Details.payload it is null and I'm sending data message from server side
});
}
- I’m sending Data message from server side instead of Notification
Data Message vs. Notification: When I used notifications instead of data messages, I encountered an issue where duplicate notifications are displayed when the app is in a terminated state. To mitigate this issue, I switched to sending data messages from my server.
Additional Context:
Here’s how I’m sending data messages from my server using Firebase Admin SDK:
const message = {
token: deviceToken,
data: {
senderName: senderName,
message: messageContent,
conversationId: conversationId,
companyId:companyId,
isGroup:'false'
}
};
try {
const response = await admin.messaging().send(message);
console.log(`Successfully sent message: ${response}`);
} catch (error) {
console.log(`Error sending message: ${error}`);
}
How to Handle notification On Tap?
2
Answers
I Have fixed the issue what I did is
I have added Message.data Into Payload so that now the notification has the Payload So I have handled it in onDidReceiveNotificationResponse Here is how i implemented it
}
onDidReceiveBackgroundNotificationResponse will run when you tap the
notification while the app is in the background or terminated.
onDidReceiveNotificationResponse will run when you tap the
notification while the app is in the foreground.
So, you can combine Firebase and local notifications to handle both cases:
If you want handle notification when app closed you send notification FCM, something like this:
};
and handle it:
i hope it helps