how to navigate when click background notification on Flutter?

10,853

Solution 1

You can use this function to navigation when the app is killed and receive notifications in the background

  FirebaseMessaging.instance
        .getInitialMessage()
        .then((RemoteMessage message) {
      print("FirebaseMessaging.getInitialMessage");
      if (message != null) {

        Navigator.of(context).pushNamed('/call');
      }
    });

This function only run once when the app open and get the last message.

You can read more at this doc: https://github.com/FirebaseExtended/flutterfire/blob/62e09975f9b3d14141585e62ddab6b98e667b7cf/docs/messaging/notifications.mdx

Solution 2

To handle notifications coming from a background state you can use the stream exposed by the FirebaseMessaging library.

FirebaseMessaging.onMessageOpenedApp.listen((remoteMessage) {
  // Handle navigation or perform any logic here
});
Share:
10,853
BIS Tech
Author by

BIS Tech

Updated on June 06, 2022

Comments

  • BIS Tech
    BIS Tech about 2 years

    Is it possible to navigate to a specified path when clicking background FCM notification?

    I created a Top-Level function and add it to the navigator path but its not working, when clicking on a background notification, it just opens the app

    I GUESS I FOUND AN ISSUE

    Now, I changed fcm configuration from home page to splash screen. The foreground doesn't navigate to the page, I think its because the Splash Screen is no longer available. When I click on the notification message, it just opens the app.

    FCM Configuration

    onBackgroundMessage: backgroundMessageHandler
    

    Top-Level function

    Future<dynamic> backgroundMessageHandler(Map<String, dynamic> message) {
      if (message.containsKey('data')) {
        getIt<NavigationService>().navigateTo('/${message['data']['screen']}');
      }
    }
    

    Payload

    const payload: admin.messaging.MessagingPayload = {
                    notification:{
                        title: `New Enquiry`,
                        body:`${customerName} published to ${subName}`,
                        badge: '1',
                        sound: 'default'
                    },
                    data: {
                        click_action: `FLUTTER_NOTIFICATION_CLICK`,
                        sound: `default`,
                        status: `chat`,
                        screen: `homePage`
                      }
                }
    

    main.dart

    GetIt getIt = GetIt.instance;
    
    void main() {
      setupLocator();
        runApp(MyApp());
    }
    

    MaterialApp

     return MaterialApp(
          navigatorKey: NavigationService().navigatorKey,
          onGenerateRoute: Router.generateRoute,
        );
    

    NavigationService and setupLocator

    class NavigationService {
      final GlobalKey<NavigatorState> navigatorKey =
          new GlobalKey<NavigatorState>();
    
      Future<dynamic> navigateTo(String routeName) {
        return navigatorKey.currentState.pushNamed(routeName);
      }
    }
    
    void setupLocator() {
      getIt.registerLazySingleton(() => NavigationService());
    }
    
  • farouk osama
    farouk osama almost 4 years
    Regardless of the screen that you want to open, what is required is to know how to open the screen by Navigator in case the application is utterly closed, thank you
  • Mr vd
    Mr vd over 3 years
    you need to subscribe event by using _firebaseMessaging.subscribeToTopic("Your topic name")..after receiving notification when the app is closed and it will redirect to that specific page when you click on notification
  • BIS Tech
    BIS Tech almost 3 years
    my question is how to navigate on BACKGROUND MODE
  • Santiago Racca
    Santiago Racca almost 3 years
    The OP was asking for a method to handle Push Notifications in BACKGROUND mode, and so the answer is correct. Your answer uses a method to handle push notifications from a TERMINATED state, which works but it is not what the OP wanted. You should read the question and comments more carefully
  • Ganesh Bhat
    Ganesh Bhat almost 3 years
    getInitialMessage() will be triggered when the app is opened via a notification from terminated state. It can be used to navigate to certain page by passing data in notification
  • Rajesh
    Rajesh over 2 years
    You are answering for on killed & onMessage, but the problem is onBackground. Ie the app is minimized by using Home Button, and unable to use any navigation process. Before 2 years it was simple to use "onResume"
  • Rajesh
    Rajesh over 2 years
    This is the perfect solution I expected. I used onResume 1yr ago! onMessageOpenedApp works perfectly. Thanks @Santiago Racca
  • Santiago Racca
    Santiago Racca over 2 years
    Glad I could help!
  • Muhammad Umair Saqib
    Muhammad Umair Saqib over 2 years
    in my case FirebaseMessaging.onMessageOpenedApp and FirebaseMessaging.instance .getInitialMessage() methods are not fired on background notification click.
  • Muhammad Umair Saqib
    Muhammad Umair Saqib about 2 years
    In my case, this method is not fired. Please guide me about this scenario.