Flutter - Firebase Cloud Messaging Navigation in onLaunch doesn't work

1,734

You can try to use getInitialMessage instead of onLaunch. I believe this will do what you want as documentation indicated the following lines:

This should be used to determine whether specific notification interaction should open the app with a specific purpose (e.g. opening a chat message, specific screen etc).

@override
void initState() {
  super.initState();
  FirebaseMessaging.instance.getInitialMessage().then((RemoteMessage message) {
    if (message != null) {
      Navigator.pushNamed(context, '/message', arguments: MessageArguments(message, true));
    }
  });
}
Share:
1,734
F.SO7
Author by

F.SO7

Updated on December 28, 2022

Comments

  • F.SO7
    F.SO7 over 1 year

    I am building an app which receives push notifications using FCM.

    I want to route to a specific screen when a notification is clicked (for example, the user's profile).

    On Android, it works perfectly fine when the app is just closed (and not "killed"), but when the app is terminated ("killed") it is not working. On iOS, it doesn't work at all.

    I am implementing it life this:

    NotificationsHandler:

    class NotificationsHandler {
      static final NotificationsHandler instance = NotificationsHandler();
    
      final _fcm = FirebaseMessaging();
    
      void onBackgroundNotificationRecevied({Function onReceived}) {
        _fcm.configure(
          onResume: (message) => onReceived(message),
          onLaunch: (message) => onReceived(message),
        );
      }
    }
    

    myMainScreen's initState:

    @override
      void initState() {
        NotificationsHandler.instance.onBackgroundNotificationRecevied(
          onReceived: (message) async {
            final userId = message['data']['userId'];
            final user = this.users.firstWhere((currentUser) => currentUser.id == userId);
    
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => UserProfileScreen(
                  user,
                ),
              ),
            );
          }
        );
        super.initState();
      }
    

    Code for sending the notifications (through an external React admin panel):

    const payload = {
        notification: {
            title: `myTitle`,
            body: `My message`,
            sound: "default",
            badge: "1",
            click_action: "FLUTTER_NOTIFICATION_CLICK",
        },
        data: {
            click_action: 'FLUTTER_NOTIFICATION_CLICK',
            userId: myUserId,
        },
    };
        
    const options = {
        priority: 'high',
        timeToLive: 60 * 60 * 24
    };
    
    admin.messaging().sendToTopic('myTopic', payload, options);
    

    Does anyone know why it isn't working?

    Thank you!