Where to store Widget controllers

Hi All,

I see some developers put Text Editing Controllers in the state management controllers or Blocs; So is it normal?

I think we don’t need to do such a thing.

For me I am handle text form fields controllers using flutter hooks, and handle text fields validations using helpers/methods.

AVOID using providers for Ephemeral state ( * generally everything that Flutter deals with a “controller” (e.g. TextEditingController))
If you are looking for a way to handle local widget state, consider using flutter_hooks instead.

https://riverpod.dev/de/docs/essentials/do_dont

It seems you are doing everything right.

1 Like

The only reason to put a TextEditingController into a business object outside of the widget is if you want to access it out side the widget.
I can imagine such situations but they should be rare.

watch_it now has a createOnce function for exactly that situation so you don’t need a StatefulWidget.

@muhammadkamel I guess that question does not really have something to do with MVVM but where to store controllers. Maybe you find a better title?

3 Likes

Can I use watch_it for multiple text input controllers?

Yes, you can use createOnce multiple times in one build Method

One thing we have to make sure is that TextEditingController or other controllers have to be disposed when they are no longer needed.

Remember to dispose of the TextEditingController when it is no longer needed. This will ensure we discard any resources used by the object.

So I usually store them in State of StatefulWidget so that I can dispose them when dispose() is called, meaning synchronizing the widget’s and controller’s lifecycle perfectly.

Or you let watch_it or flutter_hooks take care of that :wink:

Oops, I didn’t know much about watch_it. And yeah, flutter_hooks does that perfectly. They are good replacements for StatefulWidget.

1 Like

I saw this in multiple projects … the main benefit from it, to uses it to store the value of the current state of that control or access the value from any place in your widget tree… using buildWhen method or listenWhen to avoid re-building the widget … i think it’s the replacement of the dispose method

But I prefer to define it in the view

That is interesting, thank you!
Maybe you could add an example in the readme of the repo, it’s not self explanatory for boobs like me.:crossed_fingers:

Yes I know, it’s pretty new. Will add a section the next days.