Search code examples
androidflutterpush-notificationbackground-processfirebase-notifications

Flutter notification open dialog when app is killed


I'm building an app using flutter with firebase notifications.

The app displays an alert dialog once a notification is received; it's working perfectly while I'm inside the app and while outside the app (in the background but the app isn't killed, I open the notification from the panel --> the app opens and an alert dialog is displayed).

However, when the app is killed I'm able to receive the notification in the panel but when I open the app the alert dialog is not displayed.

Here is some code that might be useful:

FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      RemoteNotification? map = message.notification;
      if(map!.title == "Trip has ended"){
        try{
          showAlertDialog(navigatorKey.currentContext!, map!.title, map.body, null);
        }catch(e){print(e);}
        
      }
    });
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) async {

      RemoteNotification? map = message.notification;


      if(map!.title == "Trip has ended"){
        print("not listen trip end");

        try{
          showAlertDialog(navigatorKey.currentContext!, map!.title, map.body, null);
        }catch(e){print(e);}
        
      }

      
      

      if(map!.body != null ){
        if(map!.title == "Your driver is here"){
        String carImage = message.data['carImage'];
        print("receievedddd $carImage");
        try{
        showAlertDialog(navigatorKey.currentContext!, map!.title, map.body, carImage);
      }catch(e){print("error here $e");}
      }
      }
    });

Could someone help by suggesting what would be happening or any approach to tackling this problem? Thank you guys!


Solution

  • I refer some answers from other threads and resolved it by using this getInitialMessage()

    FirebaseMessaging.instance.getInitialMessage().then((message) {
      if (message != null) {
        RemoteNotification? notification = message.notification;
        AndroidNotification? android = message.notification?.android;
        if (notification != null && android != null) {
        //  TODO
        //  Do any logic, for example dialog
        }
      }
    });
    

    References: https://stackoverflow.com/a/72497605/15075643 https://stackoverflow.com/a/68517166/15075643