Madlad 007
Madlad 007

Reputation: 225

How can i refresh the widget on the the page A, when i return from page B?

I have a stateful Page A that contains a widget which is present in a seperate stateful class.

The widget fetches a number from sharedPreferences in its initState method and show it and when i click on the widget, it routes to Page B, Page B contains a function that change the number in the sharedPreferences.

when i go back i dont see the changes but when i reopen the app or switch to a different tab and come back, i do.

Upvotes: 1

Views: 1595

Answers (2)

CopsOnRoad
CopsOnRoad

Reputation: 267414

In page A, when you go to page B use,

Navigator.pushNamed(context, "/pageB").then((value) {
  if (value == true) {
    setState(() {
      // refresh page 1 here, you may want to reload your SharedPreferences here according to your needs
    });
  }
});

In page B, when you want to go back to page A, use

Navigator.pop(context, true);

Edit: If you don't have a named route, you may want to use following in 1st situation.

Navigator.push(context, MaterialPageRoute(builder: (context) => PageB())).then((value) {
  if (value == true) {
    setState(() {
      // refresh page 1 here, you may want to reload your SharedPreferences here according to your needs
    });
  }
});

Upvotes: 2

Sunny
Sunny

Reputation: 3265

If you are moving from pageA to pageB:

In pageA widget button click you need to call the below code:

_navigateAndDisplayData(
      BuildContext context) async {
    final returnVal = await Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => pageB()),
    );

    setState(() {
      // returnVal has true or false.
      if (returnVal){
         // Put your code here
       }

    });
  }

If you always refresh with expecting any value from pageB. Then just remove the if statement.

On other side pageB you want to send the data on pageA just used

Navigator.pop(context, true);

Upvotes: 0

Related Questions