0

I use the Firebase Cloud Messaging (FCM) in my Flutter project. The following packages:

firebase_messaging: ^8.0.0-dev.15
flutter_local_notifications: ^4.0.1+2

I know that I can handle click on push-notification when app is in background in the following way:

FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      //TODO
    });

and it works fine, but how to handle click on push-notification when application is in foreground? Can't find in the documentation as well. Could you please help me. Thanks in advance.

valerybodak
  • 4,195
  • 2
  • 42
  • 53
  • When the app is in foreground, you can use [`.onMessage()`](https://imgur.com/a/lxFJs2r) of `FirebaseMessaging`, but instead of a notification, you should show a dialog. – Lalit Fauzdar Apr 25 '22 at 20:05

2 Answers2

1

you can set the callback function on initializing

await flutterLocalNotificationsPlugin.initialize(
  const InitializationSettings(
    android: initializationSettingsAndroid,
    iOS: initializationSettingsIOS,
  ),
  onSelectNotification: handleClickNotification,
);

handleClickNotification(String? payload) {
  //your code
}
hyobbb
  • 332
  • 1
  • 9
0

Use this dependency when the app is in foreground- https://pub.dev/packages/flutter_local_notifications

Edit

FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      //TODO
    });

You are already using this code for when the app is in background. See that you are using onMessageOpenedApp. For firing the message when in foreground you can use onMessage. Example-

FirebaseMessaging.onMessage.listen((message) { 
 LocalNotificationService.display(message);
});
Pranav
  • 326
  • 1
  • 10
  • I use flutter_local_notifications: ^4.0.1+2 in my app. Could you please clarify how to handle click on notification? – valerybodak Jan 14 '22 at 06:29
  • I have edited the answer. See if it solves the question. – Pranav Jan 14 '22 at 13:29
  • @valerybodak is your question answered? – Pranav Jan 16 '22 at 05:47
  • No, because my question was about CLICK on foreground message. – valerybodak Jan 18 '22 at 08:46
  • @valerybodak Do you want to open a particular screen after clicking on it? I mean what's stopping you from clicking it? I might not understand your question completely, so could you clarify what you want to do exactly. – Pranav Jan 18 '22 at 12:07
  • How can I listen CLICK event on the foreground notification? – valerybodak Jan 18 '22 at 12:23
  • @valerybodak When the app is in foreground `FirebaseMessaging.onMessage.listen` will be fired. In that I have made a `LocalNotifcationService` which will be shown. When LocalNotifcationService is initilized we can fire an `onSelectNotification` which will run when the notification is tapped. There you can write the click event. If the doubt is how LocalNotification can be defined so that those functions can be written which will fire when tapped, then I can update the answer. – Pranav Jan 18 '22 at 17:40