Flutter how to open page from push notification, context issue - flutter

void selectNotification(String? payload) async {
print('Selected notification');
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => SearchScreen(),
),
);
}
I am using this method to open a screen when the notification is tapped, I get the print message fine but then the Navigator message shows:
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.
Im just trying to have it so if the notificaiton is tapped from foreground, background where ever the app then just pops open that screen but I cant get it to work

void selectNotification(String? payload, BuildContext context) async {
print('Selected notification');
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => SearchScreen(),
),
);
}

Use getX package and use navigation routing:
something like this:
Get.put(()=> **your page**
getX package

Related

Flutter, refresh screen after await call

Currently the only way I have to refresh the screen is using Navigator.push().
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) => this.build(context)));
}
But this only adds another screen to the stack of screens.
How can I refresh the screen after calling my print() without having to use Navigator.push()?
Thanks!
You can set your class as Stateful Widget and use:
setState(() {
// Add, edit or delete widgets
// Set a diferent value for some variable
// etc...
});
Or you can still use the Navigator but with the pushReplacement function, for example:
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (BuildContext context) => super.widget));
use setState after request api response data,
setState is a way to dynamically change the UI.
It rebuild all current screen.
We call it inside the State Object class of the StatefulWidget.

refresh previous page on Navigator.pop function

Is there any way to refresh the previous page/ stack when Navigator.pop(context) is called? I need to do the API calling of the previous page to refresh the state of the page. The navigator.pop will sometimes be an alert dialog or maybe a back button. Is there a way to do the API calling? ThankYou.
use the then function after you push another route.
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => MyHomePage(),
),
).then(
(value) {
if (value) {
//refresh here
}
},
);
and when you return to previous screen, provide the pop function a value that determines whether to perform some action.
Navigator.of(context).pop(true);
Previous page
void goToNextPage()async {
var refresh = await Navigator.push(_context, new MaterialPageRoute(
builder: (BuildContext context) => new nextPage(context))
);
if(refresh ) setState((){});
}
NextPage
Navigator.pop(context, true);

Flutter: How to perform an actions after Navigator.pushNamedAndRemoveUntil() has completed

In my Flutter app, I need to clear the Navigator stack and get back to the Home page when a certain button is pressed. To achieve that I've used Navigator.pushNamedAndRemoveUntil(context, "/", (r) => false);. I also need to call a function after the navigation has been completed, meaning that I'm now on the Home page.
I've tried calling the .whenComplete() method on Navigator.pushNamedAndRemoveUntil(), but it doesn't seem to work.
Thanks in advance.
I'd say use your function inside dipose(), so it's called when the widget is removed from the tree as you navigate to another screen.
class _MyPageState extends State<MyPage> {
// ...
// Some code
#override
void dispose() {
// Insert your function here
super.dispose();
}
// ...
}
Using didPush() method
This can be used to call your function after navigating to another screen because it returns when the push transition is complete. However, you have to do it with pushAndRemoveUntil() instead of pushNamedAndRemoveUntil(). So, you can create a PageRoute which provides didPush() method.
// Create your route
MaterialPageRoute route = MaterialPageRoute(
builder: (context) => HomePage(),
);
// Push the route onto the navigator, and then remove all the previous routes
Navigator.pushAndRemoveUntil(context, route, (r) => false);
// This returns when the push transition is complete.
route.didPush().whenComplete(() {
// Insert your function here
});
You can try as well as this code And please let me know.
gotoNewPage(context) async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
NewPage()));
/// Your logic is here.
}

flutter call a function after moving back to screen from another screen

How to call a function in flutter ,after moving back to a screen from another screen?
For Example:
Screen 1
function1(){
}
Screen2
function2(){
//Go back to screen 1 and then call function1()
}
It's simple.
Navigator.push(context, MaterialPageRoute(builder: (context)=> SecondScreen())).then((_){
// This method gets callback after your SecondScreen is popped from the stack or finished.
function1();
});
You should also refer the Flutter Navigation & Routing.
Here is the solution!
Second Screen
Navigator.pop(context, [1]);
or, if you don't want to send back any data, you can only call
Navigator.pop(context);
First Screen
Navigator.push( context, MaterialPageRoute( builder: (context) => SecondScreen(), ), ).then((value) { //do something after resuming screen
});
Imho the solutions provided here aren't valid solutions.
If you use a routes Future it may be called multiple times and will even be called in case of a forward navigation.
Instead use a NavigatorObserver:
class AppNavigationObserver extends NavigatorObserver {
#override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
print("AppNavigationObserver: ${route.settings.name}");
print("AppNavigationObserver: ${previousRoute?.settings.name}");
}
}
You can then use it for example like this:
MaterialApp(
navigatorObservers: [
AppNavigationObserver()
],
onGenerateRoute: (RouteSettings settings) {
return PageRouteBuilder(
maintainState: true,
settings: settings,
transitionDuration: const Duration(milliseconds: 300),
pageBuilder: (context, animation, secondaryAnimation) {
// Your route builder according to settings
},
);
},
)
The important part is passing onGenerateRoute's settings paramter to the PageRouteBuilder settings. Otherwise settings.arguments and settings.name will be null in the didPop handler.

Navigate to Additional Page Seconds after First Loads

Say my app starts on PageA, I'm trying to navigate to PageB 2 seconds after it loads.
Here is what I've tried...
In PageA:
Future _sleepTwo() {
return new Future.delayed(const Duration(seconds: 2), () => "sleeping...");
}
#override
void initState() {
this._sleepTwo().then((res) {
Navigator.push(
context,
new MaterialPageRoute(
builder: (BuildContext context) => PageB(),
));
});
}
But this gives me the following error:
E/flutter (22949): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: Navigator operation requested with a context that does not include a Navigator.
E/flutter (22949): 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.
I've looked everywhere but got nowhere.
I even tried wrapping everything in initState() with a Future(() => {code here});. But it didn't work.
You won't have a context if the page hasn't initialized. Insert the following code into your Widget build(BuildContext context) method.
_sleepTwo().then((res) {
Navigator.push(
context,
new MaterialPageRoute(
builder: (BuildContext context) => PageB(),
));
});
Don't use the await keyword if you want the PageA to still draw itself, and then after two seconds switch to PageB