高万祥
高万祥

Reputation: 85

TextField loses value after interacting with TextEditingController

When I add a TextEditingController to my TextFormField, the value of the text field gets reset/removed after interacting with it.

In the Code Example I removed unnecessary Widgets (for a shorter Question):

Widget build(BuildContext context) {
final usernameTextEditController = TextEditingController();
final passwordTextEditController = TextEditingController();
final confirmPasswordTextEditController = TextEditingController();
//...
                TextFormField(
                  validator: InputValidator.inputUsernameValidate,
                  controller: usernameTextEditController,
                  decoration: InputDecoration(
                    labelText: 'Your user name.',
                  ),
                ),

                TextFormField(
                  controller: passwordTextEditController,
                  validator: InputValidator.inputPasswordValidate,
                  decoration: InputDecoration(
                    labelText: 'Your password',
                  ),
                  obscureText: true,
                ),

                TextFormField(
                  controller: confirmPasswordTextEditController,
                  validator: InputValidator.inputPasswordValidate,
                  decoration: InputDecoration(
                    labelText: 'Confirm Password',
                  ),
                  obscureText: true,
                ),


//...
  }

TextField loses value

Upvotes: 1

Views: 1296

Answers (1)

afcode
afcode

Reputation: 560

Your variables are in the build()-Function, this one gets called frequently and so your Variables get initialized again and again (= “reseting”)

Move them to the Class the build()-Function is in, should fix that problem.

For detailed information about the build() and why and when it is called, please see Documentation. build method

Upvotes: 5

Related Questions