how to open particular screen on clicking on push notification for flutter

siva kumar picture siva kumar · Jan 23, 2018 · Viewed 46.9k times · Source

I am trying to achieve open specific screen on clicking push notification and my payload looks like this:

 var payload = {
        notification: {
            title: notificationTitle,
            body: notificationMessage,
            click_action:"/screena",sound:"default",
        }
    };

I am getting notification but I am unable to catch notification click event in flutter how to catch it. I am using flutter messaging

https://github.com/flutter/plugins/tree/master/packages/firebase_messaging

and my firebase push message service code looks like this

 pushMessagingService() async{
messagingreference.configure(
onMessage: (Map<String, dynamic> message) {

  print("I am here in on message");
  print(message);
},
onLaunch: (Map<String, dynamic> message) {
  print("I am here onLaunch");
  print(message);
},
onResume: (Map<String, dynamic> message) {
  print("I am hereonResume");
  print(message);
},
);
  messagingreference.requestNotificationPermissions(
  const IosNotificationSettings(sound: true, badge: true, alert: true));
 messagingreference.onIosSettingsRegistered
  .listen((IosNotificationSettings settings) {
print("Settings registered: $settings");
 });
 messagingreference.getToken().then((String token) async {


print(token);
 });
 }

here I can get the message as @xqwzts said in on message when my app is in the foreground but my question is how to catch click event from push notification raised in the system tray and navigate to the required screen.

Answer

xqwzts picture xqwzts · Jan 23, 2018

A few things here:

1- click_action has to be set to "FLUTTER_NOTIFICATION_CLICK"

2- click_action has to be set in the data section of a payload

DATA='{
  "notification": {
    "body": "this is a body",
    "title": "this is a title"
    "click_action": "FLUTTER_NOTIFICATION_CLICK",
  },
  "data": {
    "sound": "default", 
    "status": "done",
    "screen": "screenA",
  },
  "to": "<FCM TOKEN>"
}'

This should allow you to receive the message in the onMessage handler in your flutter app.

From there you can call Navigator.of(context).pushNamed(message['screen']).

If you don't have a BuildContext at that point, you can register a GlobalKey as the navigatorKey property of your MaterialApp, and use it to access your Navigator globally, via GlobalKey.currentState