Home > OS >  How to save the value of textformfield?
How to save the value of textformfield?

Time:12-24

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:

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

CodePudding user response:

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");

CodePudding user response:

Instead of calling setState and assigning values to the controller, you can give these values to the initialValue attribute of the TextFormField and then update the controllers with the Onchanged method of TextformField.

JUST LIKE SO:

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

// Adding initial value and updating it when the user edit the form
TextFormField(
   controller: nameController,
   initialValue: widget.name
   onChanged: (newValue) => nameController.text.value = newValue,
   autofocus: false,
   decoration: InputDecoration(
   labelText: 'Name',
   border: OutlineInputBorder(),),
),
  • Related