Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Navigator upon push notification opening in Flutter

I?m using Firebase Cloud Messaging to send push notifications to my flutter app through a cloud function, and within the notification I'm adding data which will define the page that will open upon the user tapping the notification.

This is the Logic that I'm using to handle the modification:

void _handleMessage(RemoteMessage message) {
     Navigator.pushNamed(context, "/shop", arguments: message.data["id"]);
     return;
}

Future<void> setupInteractedMessage() async {
    // 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 != null) {
      _handleMessage(initialMessage);
    }

    // Also handle any interaction when the app is in the background via a
    // Stream listener
    FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage);
}    

And when initializing the firebase app, I'm calling setupInteractedMessage();.

This works, but when the application is in the background and I tap on the notification, I get the following error:

[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Navigator operation requested with a context that does not include a Navigator.
The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.

Which means that I can't access the navigator. Is there a way I can fix this and thus open a specific page when the user taps on the notification?

like image 697
Fabrizio Avatar asked Sep 08 '25 04:09

Fabrizio


1 Answers

Move this line at your splash screen or any other starting screen Build.

FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage);
like image 187
Anas Nadeem Avatar answered Sep 10 '25 19:09

Anas Nadeem