简体   繁体   English

Flutter:根据父BLOC的state重置子BLOC的state

[英]Flutter: Reset state of child BLOC depending of state of parent BLOC

I need to reset state of child BLOC when state of parent BLOC is changed.当父 BLOC 的 state 更改时,我需要重置子 BLOC 的 state。 Let's say I have an image which is managed by ChildBloc which have a method for image scaling (so ChildBloc.state has a scale property).假设我有一个由ChildBloc管理的图像,它具有图像缩放方法(因此ChildBloc.state具有scale属性)。

When user scales image the current scale is saved in ChildBloc state and persistent.当用户缩放图像时,当前scale保存在ChildBloc state 中并持久存在。 When user goes out from the page and returned back the scale must be restored.当用户离开页面并返回时,必须恢复比例。

When user changes image (let's say select new item in images list and of couuse state of ParentBloc is changed then state of ChildBloc must be set to initial and any persistence must be cleared.当用户更改图像时(假设图像列表中的 select 新项目和 ParentBloc 的ParentBloc发生更改,则 ChildBloc 的ChildBloc必须设置为初始值并且必须清除任何持久性。

Any idea how do I need to link states of those BLOCs?知道我需要如何链接这些 BLOC 的状态吗? Is it a good idea to keep state of ChildBloc as part of state of ParentBloc ?将 ChildBloc 的ChildBloc作为 ParentBloc 的ParentBloc的一部分保留是个好主意吗?

It's hard to tell what the best state management approach is without knowing what the application does and how it works. state 在不知道应用程序做什么以及它如何工作的情况下,很难说出什么是最好的管理方法。

Anyway, in your case you have at least 2 options:无论如何,在您的情况下,您至少有 2 个选择:

  1. Unify the Parent and Child states .统一父子状态 This approach would solve your problem as you have all the state in a single bloc.这种方法可以解决您的问题,因为您将所有 state 都放在一个区域中。 But it could be a really big change (again, depends on how your ChildBloc is structured)但这可能是一个非常大的变化(同样,取决于您的ChildBloc的结构)
  2. Refer to ChildBloc inside a ParentBloc event .请参阅 ParentBloc 事件中的 ChildBloc I guess that when the user changes image in the ParentBloc you throw an event.我猜想当用户更改ParentBloc中的图像时,您会引发一个事件。 You could refer to che ChildBloc and throw a resetState event.您可以参考 che ChildBloc并引发resetState事件。 Something like: context.read<ChildBloc>().resetState(ResetStateEvent(...));类似于: context.read<ChildBloc>().resetState(ResetStateEvent(...)); . . You need the BuildContext to do this, but you can pass it in the ParentBloc event.您需要 BuildContext 来执行此操作,但您可以在ParentBloc事件中传递它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM