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