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

橙三吉。 提交于 2021-01-28 06:30:16

问题


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.


回答1:


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
    });
  }
});



回答2:


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);


来源:https://stackoverflow.com/questions/55632161/how-can-i-refresh-the-widget-on-the-the-page-a-when-i-return-from-page-b

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!