📜  flutter textformfield reset (1)

📅  最后修改于: 2023-12-03 15:30:48.582000             🧑  作者: Mango

Flutter Textformfield Reset

Flutter Textformfield is a widget that is used to create a form field that captures user input. It is commonly used in Flutter forms to collect data from users.

One of the common tasks you may have to perform when working with Textformfield is to reset the field after the user has submitted the form data. In this article, we will look at how to reset a Textformfield in Flutter.

Resetting Textformfield in Flutter

To reset a Textformfield in Flutter, you need to perform the following steps:

  1. Create a GlobalKey<FormState> and assign it to the Form widget that contains the Textformfield.

  2. Create a TextEditingController and assign it to the Textformfield

GlobalKey<FormState> _formKey = GlobalKey<FormState>();

final TextEditingController _controller = TextEditingController();
  1. In the onPressed callback of the button that the user clicks to submit the form, call the reset method of the FormState object associated with the GlobalKey.
onPressed: () {
  if (_formKey.currentState.validate()) {
    _formKey.currentState.save();
    // Call the reset method
    _formKey.currentState.reset();
    }
}
  1. In the onSaved callback of the Textformfield, clear the value of the TextEditingController.
onSaved: (String value) {
  // Clear the value of the controller
  _controller.clear();
},
  1. Set the value of the Textformfield to the value of the TextEditingController.
TextFormField(
  controller: _controller,
  // other properties
);
Summary

Resetting a Textformfield in Flutter is a common task you will need to perform when creating forms. By following the steps outlined in this article, you can easily reset a Textformfield in Flutter.

Remember to create a GlobalKey<FormState> and assign it to the Form widget, create a TextEditingController and assign it to the Textformfield, call the reset method of the FormState object, clear the value of the TextEditingController in the onSaved callback of the Textformfield, and set the value of the Textformfield to the value of the TextEditingController.