jinyus
jinyus

Reputation: 566

How to refresh state when navigating back

I would like to be able to navigate to the previous page in my app but I don't want the page to keep it's previous state. How would I go about doing this?

Upvotes: 1

Views: 1238

Answers (3)

Florian Gustin
Florian Gustin

Reputation: 35

Well you can manage the value you know ? Imagine the value is 'bool' :

    onPressed: () async {
              var value = await Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) {
                    return SecondPage();
                  },
                ),
              );
              // get the callback
              // handle error
              if (value) {
                try {
                  // reload your api call ?
                } catch (e) {
                  print('Errors');
                }
              }
            },

You can also wrap your data inside a Refresh indicator by manually scroll from the top to refresh your data. In that case, you might refresh whenever you want your api call ...

Think that way, your page data need to be rebuild in some way to refresh the data. By just navigating back it will not. The screen need an order from somewhere.

Upvotes: 0

hoangquyy
hoangquyy

Reputation: 2073

You can use then in Navigator to call setState after return to the previous page:

Navigator.push(context,MaterialPageRoute(builder: (context) =>NextPage())).then((_) {
  setState(() {});
});

Upvotes: 1

Florian Gustin
Florian Gustin

Reputation: 35

Which state management do you use ?

In case of classic stful stless, you might need a callback.

Assuming you are on the next page :

             onPressed: () {
                // return to the parent ancestor the [value]
                Navigator.pop(context, value);
              },

You get back with the previous page with some "value"; You need to modify the Navigator who let you handle the push to the next page;

 onPressed: () async {
                  var value = await Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) {
                        return SecondPage();
                      },
                    ),
                  );
                  // get the callback
                  // handle error
                  if (value != null) {
                    try {
                      setState(() {
                        // update your current state by the value you get from the second page
                         myUserName = value;
                      });
                    } catch (e) {
                      print('Errors');
                    }
                  }
                },

You can handle many ways to achieve this. In case you are using other state management let me know.

Upvotes: 0

Related Questions