skip to Main Content

With a Flutter form that uses TextFormField, how do I clear the text field after the form have been saved/submitted?

Do I have to use a Text controller?

3

Answers


  1. First define controller:

    TextEditingController controller = TextEditingController();
    

    then use it like this:

    TextFormField(
       controller: controller,
       onFieldSubmitted: (value) {
         controller.clear();
       },
    ),
    

    here in onFieldSubmitted you can get the value and save it in somewhere else and then clear the controller and by that TextFormField will get clear.

    Login or Signup to reply.
  2. If you are using a Form widget, add a Key to it, and after submitting the form you can do:
    _formKey.currentState?.reset();
    This will reset the status of the TextFormFields that are contained in your Form.

    Login or Signup to reply.
  3. Create a TextEditingcontroller

     final myController = TextEditingController();
    

    dispose of it after use

    
      @override
      void dispose() {
        // Clean up the controller when the widget is removed from the widget tree.
        myController.dispose();
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return TextFormField(
          controller: myController,
          onFieldSubmitted: (value) {
            //do smth with value
            // if you want to clear form field 
            myController.clear();
          },
        );
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search