Open In App

Clear TextField in Flutter

Last Updated : 02 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

TextField and TextFormField are the two most common widgets to get input from the user. They can be used in making forms, login pages, etc. In order to make their implementation effective and accurate, we need to add certain functionalities. In this article, we’ll learn how to clear TextField on certain actions.

There can be certain scenarios in your app, where you might need clear Text Fields. Suppose, you are creating a form and after submitting you are redirected to a new page, if you go back now then the entered text would still be there and this is not a sign of a good UI. So, in this scenario, you would be required to clear the TextField after submitting. 

Using a button to clear TextField:

Step 1: Create a new project and launch main.dart file. Clear the existing code.

Step 2: Import material.dart file

import 'package:flutter/material.dart';

Step 3: Create the main method which would call runApp() method and pass the name of your class to this method.

void main() => runApp(MyApp());

Step 4: Create the root class MyApp() that extends the Stateless Widget and add TextField widget as a child.

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('GeeksforGeeks'),
backgroundColor: Colors.green,
),
body: Center(
child: TextField()
)
)
);
}
}

Step 5 : Create a final variable of type TextEditingController(). This variable is used to access various properties and methods of TextField.

 final fieldText = TextEditingController();

Step 6 : Create a function clearText(). You can name it accordingly. Inside this function add fieldText.clear(); 

As mentioned above there are various properties of TextEditingController(). One of them is clear(), and we will use it to clear the TextField.

void clearText() {
fieldText.clear();
}

Step 7: Create a button and link that to clearText() method that we created in the above step. Now, whenever you would press this button TextField would be cleared.

Example: 

Dart




import 'package:flutter/material.dart';
 
void main() => runApp(MyApp());
 
class MyApp extends StatelessWidget {
  final fieldText = TextEditingController();
 
  MyApp({Key? key}) : super(key: key);
 
  void clearText() {
    fieldText.clear();
  }
 
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('GeeksforGeeks'),
          backgroundColor: Colors.green,
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // Use SizedBox for whitespace
              SizedBox(
                width: 250,
                child: TextField(
                  decoration: const InputDecoration(
                    hintText: 'Enter Something',
                    focusColor: Colors.green,
                  ),
                  controller: fieldText,
                ),
              ),
              const SizedBox(
                height: 15,
              ),
              ElevatedButton(
                onPressed: clearText,
                style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.all(Colors.green)),
                child: const Text('Clear'),
              ),
 
              // RaisedButton is deprecated and should not be used
              // Use ElevatedButton instead
               
              // RaisedButton(
              //   onPressed: clearText,
              //   color: Colors.green,
              //   textColor: Colors.white,
              //   child: const Text('Clear'),
              // ),
            ],
          ),
        ),
      ),
    );
  }
}


The above code creates a TextField with a RaisedButton. Whenever you enter something in the TextField and press the button, TextField would be cleared. Below is the output of the above implementation.

Output:

It is really necessary to add this functionality because if you are pushing a new screen above a screen that contains a form and then if you go back to the form then the values would still be there.

Clearing TextField using clear icon

Also, if you want to add a clear icon in the text field itself, then we would see it also.

Below is the image of the above-mentioned scenario:

Almost all steps, in this case, would be similar to the above-mentioned steps, the only difference would be to add the clear icon instead of the Raised Button.

TextField(
decoration: InputDecoration(
hintText: 'Enter Something',
focusColor: Colors.green,
suffixIcon: IconButton( // Icon to
icon: Icon(Icons.clear), // clear text
onPressed: clearText,
),
),
controller: fieldText,
),

In the above-mentioned code, there is a TextField and suffixIcon is added to it as a decoration. The clearText method is the same as used in the above code.

Example:

Dart




import 'package:flutter/material.dart';
 
// function to instantiate the app
void main() => runApp(MyApp());
 
class MyApp extends StatelessWidget {
  final fieldText = TextEditingController();
 
  MyApp({Key? key}) : super(key: key);
 
  void clearText() {
    fieldText.clear();
  }
 
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('GeeksforGeeks'),
          backgroundColor: Colors.green,
        ),
        body: Center(
          // Use SizedBox for whitespace
 
          child: SizedBox(
            width: 250,
            child: TextField(
              decoration: InputDecoration(
                hintText: 'Enter Something',
                focusColor: Colors.green,
                suffixIcon: IconButton(
                  icon: const Icon(Icons.clear),
                  onPressed: clearText,
                ),
              ),
              controller: fieldText,
            ),// TextField
          ), //SizedBox
        ),
      ),
    );
  }
}


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads