使用提供程序时在Flutter中清除状态 [英] Clear state in Flutter when using Provider

查看:254
本文介绍了使用提供程序时在Flutter中清除状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Flutter应用中手动清除提供商的当前状态?我的用例是,当用户退出我的应用程序,然后以新用户/不同用户的身份注册时,以前的用户状态仍存储在提供程序中,但是在重新启动应用程序时会自动清除。

How can I clear the current state of my providers manually in my Flutter app? The use case I have is when a user signs out of my app then signs up as a new/different user the previous users state is still stored in the providers, it is cleared automatically when the app is restarted however.

推荐答案

您可以使用键来硬重置子树的状态。

You can use keys to hard-reset the state of a subtree.

如果只想部分重置子树,则可以在另一个键的顶部添加一个GlobalKey。

And if you want to reset the subtree only partially, you can add a GlobalKey on the top of the other key.

最后,您将获得:

Widget build(BuildContext context) {
  return Provider(
    key: ObjectKey(someIdentifier),
    builder: (_) => Foo(),
    child: SomeSubtree(
      key: GlobalObjectKey(context),
    ),
  );
}

在这种情况下,如果 someIdentifier 更改后,提供者的状态将重置,但子树的状态将保留。

In such case, if someIdentifier changes, the state of Provider will reset but Subtree will be preserved.

这篇关于使用提供程序时在Flutter中清除状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆