Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to save the value of textformfield?

I have multiple TextFormFields that contains data pulled from Realtime Database and it gets displayed in an Edit Information page.

    final nameController = TextEditingController();
    final descriptionController = TextEditingController();

    setState(() {
      nameController.text = widget.name;
      descriptionController.text = widget.description;
    });
TextFormField(
   controller: nameController,
   autofocus: false,
   decoration: InputDecoration(
   labelText: 'Name',
   border: OutlineInputBorder(),),
),

Above codes will show name and description already in Edit Information page. However, when I type a new value for name and click on a different TextFormField, the name TextFormField goes back to its original value because of the controller. How can I save the state of the new TextFormField, if there is any, and update with the new value? Should I use onSaved or onChanged?

Information will be updated after clicking on this button:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ElevatedButton(
   onPressed: () {
   updateData(nameController.text,
   descriptionController.text, widget.passkey);
   Navigator.of(context).pop();},
   child: Text('Update')),

Update function:

  void updateData(String name, String description, var id) {
    Map<String, String> newvalue = {'name': name, 'description': description};
    databaseref.child(id).update(newvalue);
  }

>Solution :

This is due to setstate. Just remove Setstate from

setState(() {
      nameController.text = widget.name;
      descriptionController.text = widget.description;
    });

And Define your controller like

final controller = TextEditingController(text: "Your initial value");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading