Ruan
Ruan

Reputation: 4293

Flutter on page focus event?

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

Answers (2)

Constantin N.
Constantin N.

Reputation: 2839

You can make by 3 different ways depending on what you want exactly.

  1. 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(
    
          ),)
        );
      }
  1. Listen only for page2 (only if you want to check execute code on Page1)
  • page2: this is needed only if you want to execute your code on Page1 depending on the result of page2.
    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)
  • Page1: use the sent by Page2
    final result = await Navivigator.push(MaterialPageRoute(builder: (ctx)=>Page2()));

    if (result != null) {
        //do something
    }
  1. You want to listen for the whole app lifecycle events. By this way, You can check anytime when user comes back to Page1 if tasks has been correctly executed. or not
  • 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

Augustin R
Augustin R

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

Related Questions