'clearing text field when using flutter_bloc
I have a simple chat page with a ChatBloc and a ReplyBox widget, a message box with a send button.
The I would like the ReplyBox to be reusable, so not to have specific knowledge of the ChatBloc. However, I'd like to be able to control the text in the ReplyBox from the bloc. This is proving very difficult because the text field expects to use a TextEditingController.
What I've tried:
- Using
TextFormFieldinitialValueto pass into the widget the text from the bloc. Doesn't rebuild when the value changes. - Forcing a rebuild using
Key. Text is updated but focus is lost. - Making it a stateful widget with a TextEditingController, not taking the text value from the bloc, and just clearing when the button is pressed. This works ok, but it's not flexible. For example, the message would be cleared if there is a sending error, which it shouldn't.
I haven't tried managing the TextEditingController in the bloc. It seems like not the right thing to do.
Solution 1:[1]
I see the 3rd method is promising with StatefullWdiget and TextEditingController to solve your problem. I would have another bloc for the ReplyBox with events like Reset, Update, etc. In the widget I would connect the state of the ChatBloc to ReplyBloc.
Solution 2:[2]
I have asked a similar question on the repository of BLoC library. Quoting the answer provided to me by Felix Angelov, the creator itself:
I don't recommend that. The proper way imo is to maintain a TextEditingController and call clear when you want to clear the input.
You can read the answer here plus you can also check the entire question.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chop TRAN |
| Solution 2 | Shahzad Umar Baig |

