How to open my app from background and navigate to a page on receiving a notification message in flutter?

1k views Asked by At

I need to open the app automatically on receiving a notification message. Is it possible in flutter?

Below is the code for handling the background messages and it works.

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  print('Handling a background message ${message.messageId}');
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  ......
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MyApp()
    )
  );

What I need is I have a separate page that needs to popup when that particular function is executed (When the app is in background). Can anyone help me out with this! Thanks in advance

1

There are 1 answers

1
Amitha Mohanan On
    await _firebaseMessaging.subscribeToTopic('topic name');
    _firebaseMessaging.configure
    (
        
        // The onMessage function triggers when the notification is 
        received while we are running the app.
        onMessage: (message) async
        {
            setState(()
            {
                messageTitle = message["notification"]["title"];
                messageDescription = message["notification"]["description"];
                notificationAlert = "New Notification Alert";
            });

        },
        // The onResume function triggers when we receive the notification alert in the device notification bar and opens the app through the push notification itself. In this case, the app can be running in the background or not running at all.
        onResume: (message) async
        {
            print("ON RESUME");

            setState(() 
            {
                messageTitle = message["data"]["title"];
                messageDescription = message["notification"]["description"];
                notificationAlert = "Application opened from Notification";
            });
        },
        onLaunch: (Map<String, dynamic> message) async // Called when app is terminated
        {
            print("onLaunch: $message");

            var data = message["data"];

            print(data);

            // Navigator.pushNamed(context, "details");
        }
    );

In this code the onResume function will help you run the app from background so you can code inside onResume and navigate to your specified screen.