Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Dart 当我从B页返回时,如何刷新A页上的小部件?_Dart_Flutter - Fatal编程技术网

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

Dart 当我从B页返回时,如何刷新A页上的小部件?,dart,flutter,Dart,Flutter,我有一个有状态的页面,其中包含一个小部件,它存在于一个单独的有状态类中 小部件在其initState方法中从SharedReferences获取一个数字并显示它,当我单击小部件时,它将路由到B页,B页包含一个更改SharedReferences中数字的函数 当我返回时,我看不到更改,但当我重新打开应用程序或切换到其他选项卡并返回时,我会看到更改。在a页中,当您转到B页时,请使用 Navigator.pushNamed(context, "/pageB").then((value) { if

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

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


当我返回时,我看不到更改,但当我重新打开应用程序或切换到其他选项卡并返回时,我会看到更改。

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

如果您正在从pageA移动到pageB:

在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语句

在pageB的另一端,您希望发送刚刚使用的pageA上的数据

Navigator.pop(context, true);

刚刚找到一个放置
Navigator.pop(context,true)的好地方
,在其属性
onWillPop
中与
WillPopScope
”一起使用,确保每当使用后退按钮、后退箭头等方式弹出页面B时,该小部件总是会更新。是的,您可以将其放在那里,这一切都取决于您的需要。