iShah
iShah

Reputation: 149

Flutter TextField/TextFormField does not update its value on setState()

I have the following component on my flutter page.

TextFormField(
                    controller: surveyDateController, 
                    decoration: InputDecoration(
                      border: OutlineInputBorder(),
                      hintText: 'Survey Date',
                    ),
                  ),

And i have the following controller for the above control

  final surveyDateController = TextEditingController();

The data is coming from _data.leadSurvey[0].title which is loaded from an API. Once the data is loaded I am calling the setState method as follows:

setState(() {
        _data = data;
      });

But the data in the TextFormField is not getting updated. Tried using the initialValue property but it generates a null error.

Any help guys?

Upvotes: 1

Views: 3361

Answers (5)

Etornam
Etornam

Reputation: 503

To give the TextFormField a default value:

final surveyDateController = TextEditingController(text: 'initial data here');

To re-assign the TextFormField a value:

surveyDateController.text = _data;

Upvotes: 0

Abbasihsn
Abbasihsn

Reputation: 2171

let's say you have $your_text_controller$ and have assigned it to your text field as follow:

TextFormField(
                    controller: surveyDateController, 
                    decoration: InputDecoration(
                      border: OutlineInputBorder(),
                      hintText: 'Survey Date',
                    ),
                  ),

now, you can set the text of this text field by calling this function everywhere you want:

void setText(){

    setState((){
        surveyDateController.text = "Your Text"; // Ex. _data.leadSurvey[0].title
    });
}

Upvotes: 0

Moklesur Rahman
Moklesur Rahman

Reputation: 791

Set data to the controller in the setState()

  setState(() {
        _data = data;
        surveyDateController.text = _data.leadSurvey[0].title
      });

Upvotes: 2

Jhoan River
Jhoan River

Reputation: 86

after you get the data String from the server

then set your editing controller (surverDateController)

surveyDateController.text = _data.leadSurvey[0].title

Upvotes: 0

Chris Pi
Chris Pi

Reputation: 612

I am not completely sure where data should appear, but if you want it to appear in your TextFormField, I guess you have to call surveyDateController.value = data

Upvotes: 0

Related Questions