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:
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
});
}
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?
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:
/// handle when app is minimized or in foreground
void onDidReceiveNotificationResponse(
NotificationResponse notificationResponse) async {
final String? payload = notificationResponse.payload;
if (notificationResponse.payload != null &&
notificationResponse.payload!.isNotEmpty) {
/// your code
}})
If you want handle notification when app closed you send notification FCM, something like this:
const message = {
token: deviceToken,
notification: {
title: Test,
body: test body
}
data: {
senderName: senderName,
message: messageContent,
conversationId: conversationId,
companyId:companyId,
isGroup:'false'
}
};
and handle it:
var initMessage = await FirebaseMessaging.instance.getInitialMessage();
i hope it helps