我在Flutter中有一个带有按钮的StatefulWidget,它使用Navigator.push()将我导航到另一个StatefulWidget。在第二个小部件上,我正在更改全局状态(一些用户首选项)。当我从第二个小部件回到第一个时,使用Navigator.pop(),第一个小部件处于旧状态,但我想强制它重新加载。知道怎么做吗?我有一个想法,但看起来很难看:

弹出以删除第二个小部件(当前小部件) 再次弹出以删除第一个小部件(前一个) 推送第一个小部件(它应该强制重绘)


当前回答

简单的技巧就是使用导航器。pushReplacement方法

第1页

Navigator.pushReplacement(
  context,
  MaterialPageRoute(
    builder: (context) => Page2(),
  ),
);

第二页

Navigator.pushReplacement(
  context,
  MaterialPageRoute(
    builder: (context) => Page1(),
  ),
);

其他回答

非常简单地使用"then"在你推送后,当导航器弹出时,它将触发setState,视图将刷新。

领航员...废话的push()。然后(价值)= > setState署(){})

对我来说奏效了:

...
onPressed: (){pushUpdate('/somePageName');}
...

pushUpdate (string pageName) async {      //in the same class
  await pushPage(context, pageName);
  setState(() {});
}


//---------------------------------------------
//general sub
pushPage (context, namePage) async {
  await Navigator.pushNamed(context, namePage);
}

在这种情况下,不管你如何弹出(与按钮在UI或“返回”在android)更新将完成。

这段简单的代码会转到根目录,即使没有setState也会重新加载状态:

Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context) => MainPage()),  (Route<dynamic> route) => false,);   //// this MainPage is your page to refresh

您可以在弹出上下文时传递回一个动态结果,然后在值为true时调用setState((){}),否则就保持状态不变。

我粘贴了一些代码片段供您参考。

handleClear() async {
    try {
      var delete = await deleteLoanWarning(
        context,
        'Clear Notifications?',
        'Are you sure you want to clear notifications. This action cannot be undone',
      );
      if (delete.toString() == 'true') {
        //call setState here to rebuild your state.

      }
    } catch (error) {
      print('error clearing notifications' + error.toString());
             }
  }



Future<bool> deleteLoanWarning(BuildContext context, String title, String msg) async {

  return await showDialog<bool>(
        context: context,
        child: new AlertDialog(
          title: new Text(
            title,
            style: new TextStyle(fontWeight: fontWeight, color: CustomColors.continueButton),
            textAlign: TextAlign.center,
          ),
          content: new Text(
            msg,
            textAlign: TextAlign.justify,
          ),
          actions: <Widget>[
            new Container(
              decoration: boxDecoration(),
              child: new MaterialButton(
                child: new Text('NO',),
                onPressed: () {
                  Navigator.of(context).pop(false);
                },
              ),
            ),
            new Container(
              decoration: boxDecoration(),
              child: new MaterialButton(
                child: new Text('YES', ),
                onPressed: () {
                  Navigator.of(context).pop(true);
                },
              ),
            ),
          ],
        ),
      ) ??
      false;
}

问候, Mahi

对我来说,这似乎奏效:

Navigator.of(context).pushNamed("/myRoute").then((value) => setState(() {}));

然后在子进程中调用Navigator.pop()。