'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?
Solution 1:[1]
Move this line at your splash screen or any other starting screen Build.
FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage);
Solution 2:[2]
I had this same problem with the same scenario (launching a view from a push notification) and solved it by making MaterialApp
the root of my app widget tree rather than my own widget (as per this answer and others):
void main() {
runApp(MaterialApp(
title: 'Navigation Basics',
home: MyApp(),
));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | mgalgs |