0

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.

  • Can you [edit] the question to include more code? – MendelG Aug 13 '23 at 18:20
  • @MendelG sure, what part of the code would help? – Promise App Aug 13 '23 at 18:36
  • @pskink `...` is a flutter expression for [spreading](https://stackoverflow.com/questions/57900901/whats-the-usage-of-three-dots-in-dart-list). My function `_buildSubTextField` originally returns a List of widgets that's why I spread it – Promise App Aug 13 '23 at 19:14
  • Having builder functions like your _buildSubTextField that return a Widget is considered a Flutter anti-pattern. You should get in the habit of creating new widget classes that extend StatelessWidget or StatefulWidget. You'll end up with much more efficient code. – John Weidner Aug 13 '23 at 19:18

2 Answers2

0

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. The build method will get called whenever you call setState.

Create the TextEditingController in initState or as a variable in the StatefulWidget. Just don't create it in a build() method.

John Weidner
  • 2,055
  • 3
  • 18
  • 31
0

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),
  },

Franklin Diaz
  • 309
  • 1
  • 5