如何在使用 pop 时重新加载或调用一些函数 initState()

Posted

技术标签:

【中文标题】如何在使用 pop 时重新加载或调用一些函数 initState()【英文标题】:How to reload or call some function initState() in flutter while using pop 【发布时间】:2020-02-11 05:21:26 【问题描述】:

当用户单击返回或我在第二个屏幕中使用Navigator.pop() 时,我正在尝试运行一些方法。

我有两个屏幕。

    设置画面 编辑屏幕

编辑后,我将用户弹出到第一秒。现在在第一个屏幕中我使用SharedPreference。但是当用户回到第一个屏幕时,我需要重新运行一个方法。我怎样才能做到这一点?

【问题讨论】:

【参考方案1】:

在从Settings 屏幕导航到Edit 屏幕时,使用它(在您的Settings 屏幕内)

Navigator.pushNamed(context, "/editScreen").then((_) 
  // you have come back to your Settings screen 
  yourSharedPreferenceCode();
);

如果您只想在Edit 屏幕上发生的某些事件上运行此代码,您可以在Edit 屏幕中使用pop 方法,例如

Navigator.pop(context, true); // pass true value

上面的代码应该是:

Navigator.pushNamed(context, "/editScreen").then((value) 
  if (value) // if true and you have come back to your Settings screen 
    yourSharedPreferenceCode();
);

编辑:

async-await 看起来像:

bool value = await Navigator.pushNamed(context, "/editScreen");
if (value) // if true and you have come back to your Settings screen 
  yourSharedPreferenceCode();

【讨论】:

asyncawait 的代码会是什么样子?

以上是关于如何在使用 pop 时重新加载或调用一些函数 initState()的主要内容,如果未能解决你的问题,请参考以下文章