Flutter: Adding a Clear Button to a TextField (2021)

Last updated on April 3, 2021 A Goodman Loading... Post a comment

This article shows you how to add a clear button to a TextField in a Flutter application so that a user can quickly remove the text he or she has entered.

What is the point?

We’ll create a TextEditiongController (let’s say it’s named _controller) and connect it to the TextField:

final TextEditingController _controller = TextEditingController();
/* ... */ 

TextField(
   controller: _controller,
   /* ... */
}

To empty the TextFiled, call the clear() method, like this:

_controller.clear();

To display the clear button, we use the suffixIcon property of the InputDecroation class:

TextFiled(
  decoration: InputDecoration(
    suffixIcon: // The button here
  ),
)

For more clarity, see the complete exanple below.

Example

Preview

This example app contains a TextField in the center of the screen:

  • If the TextField is blank then the clear button is invisible (actually, it doesn’t exist because we set suffixIcon to null).
  • As soon as the user enters something, the button will show up.
  • When the button is pressed, the TextField will be cleared and the button will go away.

Here’s how it works:

The code

Below’s the full source code in main.dart with explanations within the comments:

// main.dart
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // The controller for the text field
  final TextEditingController _controller = TextEditingController();

  // This function is triggered when the clear buttion is pressed
  void _clearTextField() {
    // Clear everything in the text field
    _controller.clear();
    // Call setState to update the UI
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Kindacode.com'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(30),
        child: Center(
          child: TextField(
            controller: _controller,
            onChanged: (value) {
              // Call setState to update the UI
              setState(() {});
            },
            decoration: InputDecoration(
              labelText: 'Search',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.search),
              suffixIcon: _controller.text.length == 0
                  ? null // Show nothing if the text field is empty
                  : IconButton(
                      icon: Icon(Icons.clear),
                      onPressed: _clearTextField,
                    ), // Show the clear button if the text field has something
            ),
          ),
        ),
      ),
    );
  }
}

Conclusion

You’ve learned how to create a clear button for a TextField widget in Flutter. Explore more about the TextField widget and other stuff in Flutter by taking a look at the following articles:

You can also check out our Flutter topic page or Dart topic page for the latest tutorials and examples.

Related Articles

guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x