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 notifications in flutter. So in this article, we will go through how to open particular screen on clicking on push notification for flutter.

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

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

Users need to payload like the below:

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

So our service class will have a code snippet like the one 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 change 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 the 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 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 to 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 about iOS.
iOS Button Click
iOS Button Click

Conclusion:

So in this article, we will go through how to open a particular screen on 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.

Abhishek Dhanani

Written by Abhishek Dhanani

Abhishek Dhanani, a skilled software developer with 3+ years of experience, masters Dart, JavaScript, TypeScript, and frameworks like Flutter and NodeJS. Proficient in MySQL, Firebase, and cloud platforms AWS and GCP, he delivers innovative digital solutions.

Leave a comment

Your email address will not be published. Required fields are marked *

Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Build Your Agile Team

Hire Skilled Developer From Us

"*" indicates required fields

✓ Valid number ✕ Invalid number

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields

✓ Valid number ✕ Invalid number