简体   繁体   中英

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. 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).

When user scales image the current scale is saved in ChildBloc state and persistent. 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.

Any idea how do I need to link states of those BLOCs? Is it a good idea to keep state of ChildBloc as part of state of ParentBloc ?

It's hard to tell what the best state management approach is without knowing what the application does and how it works.

Anyway, in your case you have at least 2 options:

  1. Unify the Parent and Child states . This approach would solve your problem as you have all the state in a single bloc. But it could be a really big change (again, depends on how your ChildBloc is structured)
  2. Refer to ChildBloc inside a ParentBloc event . I guess that when the user changes image in the ParentBloc you throw an event. You could refer to che ChildBloc and throw a resetState event. Something like: context.read<ChildBloc>().resetState(ResetStateEvent(...)); . You need the BuildContext to do this, but you can pass it in the ParentBloc event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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