Reputation: 4293
initState() will always call on the initialization of a page, and thats great.
But, what if I have 2 screens
Screen 1 navigates to screen 2. Now, when you press back on page 2 (pop) is there an event on page 1 that knows we are back again?
In other words, can Screen 1 fire an event on the back press of page 2?
This is useful to set the state, of say, a global variable that changed on screen 2, so screen 1 can update accordingly
Upvotes: 7
Views: 8277
Reputation: 2839
You can make by 3 different ways depending on what you want exactly.
popEvents
(my favourite): You can use WillPopScope
widget on page 2 to prevent back buttons to exit the page. @override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: (){
return Future.value(a==b); //Replace by your conditionals here. false means you're block back action for this page
},
child: Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
),)
);
}
Navigator.pop(data);//this is the data you want to send back to Page1
//if user presses back button, it's same like Navigator.pop(null)
final result = await Navivigator.push(MaterialPageRoute(builder: (ctx)=>Page2()));
if (result != null) {
//do something
}
Init binding
WidgetsFlutterBinding.ensureInitialized();
In page One add WidgetsBindingObserver
mixin to your page
class Page1State extends State<Page1> with WidgetsBindingObserver
Override didChangeAppLicycleState
method: this will pass the current state of your page or the whole app state event like going background...
@override
void didChangeAppLicycleState(AppLifecycleState state){
if(state = AppLifecycleState.paused){
//do whatever you want here
}
}
Upvotes: 1
Reputation: 7819
You can await
Navigator.push()
which will resolve when route is popped.
In Screen1 :
await Navigator.push(context, Screen2);
// Do something when Screen2 is popped
You can also pass data from Screen2
to Screen1
with pop()
:
In Screen2 :
Navigator.pop(context, data);
In Screen1 :
final dataFromScreen2 = await Navigator.push(context, Screen2);
Upvotes: 13