Bloc: Handling state for a form including the values of its fields in a BLoC

Created on 11 Mar 2019  路  4Comments  路  Source: felangel/bloc

I have a form in a tab. I don't want to lose the form's values when I switch tabs, so I keep all that state in a long lived BLoC. The form also needs the regular Valid, Invalid, Loading states.

It works like this:
The form sends an 'init' event, the BLoC sends a 'values' state.
Whenever the form gets 'values', it sets those values in its own state and sends a 'ready' event. The builder populates the controls using the form's own state variables.
On 'ready', the BLoC sends either Valid or Invalid so that the form shows error message or enables the submit button.
On text fields change or switch toggle, events are sent for the BLoC to update the current values.

Everything works, but is this how it's supposed to be done? I don't like the idea of having state variables both in the form and the BLoC (and the 'values' state!). Any ideas to simplify this design?

question

Most helpful comment

That's it, thanks a lot... nice library 馃憦

All 4 comments

@gbuela thanks for opening an issue!

Regarding your question, I鈥檇 recommend modeling the form state in a way that contains both form values as well as whether or not each field is valid.

Let me know if that helps and if you give me a few hours I can put together a simple form validation example 馃憤

You can definitey simplify your approach to have all the state maintained by the bloc. 馃槃

OK so the state provided by the bloc would always be an object of the same class, containing all form values and an enum with form status (valid, invalid, loading -- in my particular case I don't need per-field status). Sounds good, thanks!

Yeah exactly that鈥檚 one way to do it. 馃憤

I鈥檒l update the login form in the flutter_login example to have some basic form validation just so there鈥檚 an example for people to look at.

Let me know if you have any other questions and thanks again for opening this issue!

That's it, thanks a lot... nice library 馃憦

Was this page helpful?
0 / 5 - 0 ratings

Related issues

RobPFarley picture RobPFarley  路  3Comments

nerder picture nerder  路  3Comments

krusek picture krusek  路  3Comments

nhwilly picture nhwilly  路  3Comments

shawnchan2014 picture shawnchan2014  路  3Comments