📅  最后修改于: 2023-12-03 15:30:48.582000             🧑  作者: Mango
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.
To reset a Textformfield in Flutter, you need to perform the following steps:
Create a GlobalKey<FormState>
and assign it to the Form
widget that contains the Textformfield.
Create a TextEditingController
and assign it to the Textformfield
GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final TextEditingController _controller = TextEditingController();
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();
}
}
onSaved
callback of the Textformfield, clear the value of the TextEditingController
.onSaved: (String value) {
// Clear the value of the controller
_controller.clear();
},
TextEditingController
.TextFormField(
controller: _controller,
// other properties
);
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
.