How can I call a function as soon as I go back to the main screen? - Flutter

1k Views Asked by At

Hello,

From the main screen of my app, pressing a button switches to another screen.

IconButton(
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) {
                            return screen2();
                          },
                        ),
                      );
                    },

When I am in screen2 and I want to go back or I can press a button. Navigator.pop(context); or press the android back button.

How can I call a function as soon as I go back to the main screen?

Thank you.

1

There are 1 best solutions below

3
7eg On

From what I understood you want to trigger a function when you go to the previous page!

So, Make the main screen as a Stateful widget and then initialize an init state and inside the init state put the function you want to trigger

Such as like this below code

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    FunctionYouWantToTrigger();
  }