skip to Main Content

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:

  1. 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 


      });
}

  1. 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


  1. Chosen as BEST ANSWER

    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

    static void display(RemoteMessage message) async {
    try {
      final String senderName = message.data['senderName'] ?? '';
      final String messageContent = message.data['message'] ?? '';
      final String conversationId = message.data['conversationId'] ?? '';
      final int notificationId = conversationId.hashCode;
    
      String? previousBody = _storedNotificationBodies[conversationId];
      String updatedBody = previousBody != null
          ? '$previousBodyn$messageContent'
          : messageContent;
    
      List<String> lines = updatedBody.split('n');
    
      AndroidNotificationDetails androidDetails = AndroidNotificationDetails(
        "cruxtalk_channel",
        "Cruxtalk Notifications",
        importance: Importance.high,
        priority: Priority.high,
        styleInformation: InboxStyleInformation(
          lines,
          contentTitle: senderName,
          summaryText: 'You have ${lines.length} new messages',
        ),
      );
    
      NotificationDetails notificationDetails = NotificationDetails(
        android: androidDetails,
      );
    
      **String payload = jsonEncode(message.data);**
    
      await _localNotificationsPlugin.show(
        notificationId,
        senderName,
        null,
        notificationDetails,
        payload: payload,
      );
    
      _storedNotificationBodies[conversationId] = updatedBody;
    } catch (e) {
      print('Error displaying notification: $e');
    }
    

    }

     _localNotificationsPlugin.initialize(
      initSettings,
      onDidReceiveNotificationResponse: (details) {
        print('Details: $details');
        print('On Notification tapped: ${details.payload}');
        print('${details.id}');
    
        // Handle the payload here
        if (details.payload != null) {
          Map<String, dynamic> payloadData = jsonDecode(details.payload!);
          print('Payload data: $payloadData');
          handleNotificationTap(payloadData);
        }
      },
    );
    

    1. onDidReceiveBackgroundNotificationResponse will run when you tap the
      notification while the app is in the background or terminated.

    2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search