13

Do I have to create more than one TextEditingController for every TextField example

var oneController = TextEditingController();
var twoController = TextEditingController();

then

TextField(
   controller: oneController,
   decoration: new InputDecoration(labelText: "add type *income"),
),
TextField(
   controller: twoController,
   decoration: new InputDecoration(labelText: "Enter a number"),
   keyboardType: TextInputType.number,
),

or is there a way to use just one?

Kagimura
  • 397
  • 1
  • 7
  • 20

2 Answers2

19

Do I have to create more than one TextEditingController for every TextField?

Yes. A controller allows you to control and access the current state of the field,

Here, it allows you to know the current user input, so you can read or change what's selected by the user. You could also provide an initial value for each field.

If you use the same controller, the same thing will happen in both TextFields at the same time. For instance: when the user types a letter on one field, it shows up on the other as well.

If you have a form or too many fields, you may want to use other solutions like the TextFormField, which can also be used without a controller to validate and save user input all at once for multiple fields inside a Form Widget.

More about the TextEditingController on the docs.

George
  • 6,886
  • 3
  • 44
  • 56
  • Glad to help :) @MrKale – George Oct 13 '19 at 01:47
  • Hi there ! Just wondering if there was any documentation to use TextFormField without a controller to validate and save user input all at once for multiple fields inside a Form Widget. – Gene Feb 08 '21 at 19:49
  • 1
    @Gene I believe you can find it here on SO. But here's some info: the TextFormField has parameters onSaved and validator. The FormState has a method validate(). When the user press the submit button, you call validate() on the form, which will execute the validator. If every field passes, it will call onSaved, which should write the value of the field to a variable of your choice, maybe an attribute of an object. I have implemented this here, [check this code](https://github.com/DevMobUFRJ/redesign/blob/master/lib/modulos/forum/forum_post_form.dart) for an example. – George Feb 10 '21 at 21:09
3

You can use Something Similar to this. Then Simply use them like array wherever you want to.

List<TextEditingController> myController =
      List.generate(5, (i) => TextEditingController());
  • And next? I do `.addListener()` to each of these, but in the listener method it's impossible to distinguish from which controller the event came – Thomas Weller Oct 22 '21 at 12:51