user54517
user54517

Reputation: 2420

TextField & BLoC : pre-filling a field

I have a screen with a form that I use to post an ad and I use that same screen to edit an ad. When I want to edit an ad, the form is pre-fill with the content of the ad. I do that by giving the text to display to a TextEditingController.

At the same time, I use the BLoC pattern to manage the business logic of my app, and I yield a new state in the onChange property of the Textfield. Because of that, the textfield is built at every single change and as a result, the TextEditingController is also built preventing me from changing the text of the field.

 TextField(
      controller: isUpdate ? 
        TextEditingController(
          text: isUpdate == true ? myAd.property.toString() //as it builds at every single change, the text can't be modified 
            : null,
        ): null,
      onChanged: (newValue) {
         context.read<MyBloc>().add(TitleChanged(value: newValue))

So is there a way for me to pre-fill the field, but only once -not at every single build-, so that I can continue to edit it ?

Upvotes: 0

Views: 1560

Answers (2)

dkap
dkap

Reputation: 237

You could include the Text as a String in your Blocs state so instead of using myAd.property.toString() you use state.formText. Anytime you change the form using your TitleChangedevent, you also update the formText in your bloc.

Upvotes: 2

YoBo
YoBo

Reputation: 2529

Change the code to use TextFormField and set initialValue

 TextFormField(
      initialValue: isUpdate ? myAd.property.toString(): null,
      onChanged: (newValue) {
         context.read<MyBloc>().add(TitleChanged(value: newValue))

Upvotes: 1

Related Questions