Use Navigator upon push notification opening in Flutter
Move this line at your splash screen or any other starting screen Build.
FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage);
Fabrizio
Updated on December 31, 2022Comments
-
Fabrizio over 1 year
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?
-
Pokaboom almost 3 yearsuse a navigatorKey. give it to materialApp and then use same key for navigation. so you need to define that key somewhere you can access it where ever you want
-
-
Anas Nadeem almost 3 yearsOnly this line FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage); and the _handleMessage function
-
Fabrizio almost 3 yearsI am already doing it, my problem is that the function _handleMessage runs but it complains about the missing navigator.
-
Anas Nadeem almost 3 yearscan you send your main.dart complete code
-
Fabrizio almost 3 yearsThe app is a bit complex right now, I'll try my best to add to the question any relevant parts.
-
Anas Nadeem almost 3 yearsok just copy paste the MaterialApp widget of your app from main.dart
-
Fabrizio almost 3 yearsLet us continue this discussion in chat.