当我从页面B返回时,如何刷新页面A上的小部件?

问题描述 投票:1回答:2

我有一个有状态的页面A,其中包含一个小部件,该小部件存在于一个单独的有状态类中。

小部件从其initState方法中的sharedPreferences中获取一个数字并显示它,当我单击小部件时,它将路由到页面B,页面B包含一个更改sharedPreferences中的数字的函数。

当我回去时,我看不到变化,但当我重新打开应用程序或切换到另一个选项卡然后回来时,我这样做。

dart flutter
2个回答
1
投票

在页面A中,当您转到页面B使用时,

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

在页面B中,当您想要返回到页面A时,请使用

Navigator.pop(context, true);

编辑:如果您没有命名路线,您可能希望在第一种情况下使用以下内容。

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

0
投票

如果您要从一个页面移动到另一个页面:

在pageA小部件按钮中单击,您需要调用以下代码:

_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
       }

    });
  }

如果你总是刷新,期望来自pageB的任何值。然后只需删除if语句。

在另一侧页面上,您希望在刚刚使用的页面上发送数据

Navigator.pop(context, true);
© www.soinside.com 2019 - 2024. All rights reserved.