How to Open Particular Screen on Clicking on Push Notification For Flutter ?

· 5 min read
How to Open Particular Screen on Clicking on Push Notification For Flutter
How to Open Particular Screen on Clicking on Push Notification For Flutter

Earlier we have been through How to implement push notification in flutter. So in this article, we will go through how to open a particular screen by clicking on the push notification for a flutter.

Are you ready for the same? Let’s get started.

How to Open Particular Screen on Clicking on Push Notification For Flutter??

User need to payload like a below:

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

So our service class will have a code snippet like the below:

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);
 });
 }

So basically, we need to changes few things like the below:

  • click_action has to be set to “FLUTTER_NOTIFICATION_CLICK
  • 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>"
    }'

    So 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’]))

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

The following example will navigate to a specific page.

” THE CODE IS TAKEN FROM THE FIREBASE MESSAGING PLUGIN EXAMPLE CODE ONLY AND IT NAVIGATES TO A NAMED PAGE, IN WHICH THE DATA WE SENT VIA FIREBASE CONSOLE ”

FCM
FCM
  • Step-1: pass one key-value pair in the firebase notification as click_action: FLUTTER_CLICK_ACTION.
  • Step-2: Using step 1 you’ll receive the onTap callback of notification inside onResume or onLaunch method.
  • Step-3: Perform the following scenario for navigating to a specific screen on click of notification.
    • When you build your MaterialApp, pass a navigatorKey parameter which specifies the key to use for the navigator and then assign that key to your material app as shown below:
      class _MyHomePageState extends State<MyHomePage> {
        final GlobalKey<NavigatorState> navigatorKey = GlobalKey(debugLabel: "Main Navigator");
      
        @override
        Widget build(BuildContext context) {
          return new MaterialApp(
            navigatorKey: navigatorKey,
            home: new Scaffold(
              appBar: AppBar(),
              body: new Container(),
            ),
          );
        }
      }

So now, from the onResume() or onLuanch() method navigate to your screen using the below line of code:

navigatorKey.currentState.push(
   MaterialPageRoute(builder: (_) => Dashboard())
);
  • Use firebase_messaging: “^8.0.0-dev.10”. So you can also try with the below code snippet.
    class Application extends StatefulWidget {
      @override
      State<StatefulWidget> createState() => _Application();
    }
    
    class _Application extends State<Application> {
      @override
      void initState() async {
        super.initState();
    
        // Get any messages which caused the application to open from
        // a terminated state.
        RemoteMessage initialMessage =
            await FirebaseMessaging.instance.getInitialMessage();
    
        // If the message also contains a data property with a "type" of "chat",
        // navigate to a chat screen
        if (initialMessage?.data['type'] == 'chat') {
          Navigator.pushNamed(context, '/chat',
              arguments: ChatArguments(initialMessage));
        }
    
        // Also handle any interaction when the app is in the background via a
        // Stream listener
        FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
          if (message.data['type'] == 'chat') {
            Navigator.pushNamed(context, '/chat',
              arguments: ChatArguments(message));
          }
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Text("...");
      }
    }
  • You need to add this code in the AndroidManifest.xml file. You can have anything as ‘Click_Action‘, but it needs to be the same as it is in the manifest file. Not sure of iOS.
iOS Button Click
iOS Button Click

Conclusion:

So in this article, we will go through how to open a particular screen by clicking on the push notification for flutter.

Thanks for being with us on a flutter journey !!!

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Leave a Reply