skip to Main Content

I have the following function:

 _buildSubTextField(TextEditingController fieldController) {
    affirmationControllers.add(fieldController);
    return TextField(
          onChange: (value) {
            setState(() {});
          },
          controller: fieldController,
      );
}

That I call in build function:

if (state.addField) ...{
    ..._buildSubTextField(TextEditingController()),
  },

The Problem is that after the field is dynamically added to the page, I can’t type in it. The letters don’t get added.

2

Answers


  1. For your issue, the main thing to look at is where you create the TextEditingController(). You say it is in a build() method. This means that every time the build() function happens you are creating a new TextEditingController which will erase whatever you had typed in.

    You probably need a StatefulWidget and create the TextEditingController in initState or as a variable in the StatefulWidget. Just don’t create it in a build() method.

    Login or Signup to reply.
  2. The issue is that every time he writes in the input field, the onChanged, he performs a setState(() {}); and what this does is reload the control field Controller that he has with an empty text.

    try:

      _buildSubTextField(TextEditingController fieldController) {
        // affirmationControllers.add(fieldController);
        return TextField(
          onChanged: (value) {
            //setState(() {});
          },
          controller: fieldController,
        );
      }
    

    or the most correct

      _buildSubTextField(TextEditingController fieldController) {
         affirmationControllers.add(fieldController); 
        return TextField(
          onChanged: (value) {
            setState(() {});
          },
          controller: fieldController,
        );
      }
    
    ...
     //Add a TextEditingController
      TextEditingController textEditingController = TextEditingController();
    
    ...
    
    if (state.addField) ...{
        ..._buildSubTextField(textEditingController),
      },
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search