How to Clear TextField in Flutter

Users always want a clear option with TextField so that they don’t need to back press many times to make the field empty. In this blog post, let’s see how to clear TextField in flutter.

The TextField widget acts as text input in flutter. If you don’t know how to add a TextField in flutter then I suggest you to check out my blog post how to add text input in flutter.

In this flutter tutorial, we make use of TextField controller and the method clear. There’s a TextField and a RaisedButton. When the RaisedButton is pressed the TextField gets cleared. Go through the example below for proper understanding.

import 'package:flutter/material.dart';

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

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Text Input Clear Example',
      home: MyInput(),
    );
  }
}

// Define a custom Form widget.
class MyInput extends StatefulWidget {
  @override
  _MyInputState createState() => _MyInputState();
}

// Define a corresponding State class.
// This class holds the data related to the Form.
class _MyInputState extends State<MyInput> {
  // Create a text controller and use it to retrieve the current value
  // of the TextField.
  final myController = TextEditingController();

  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    myController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Text Input Clear Tutorial'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Center(child: Column(children: <Widget>[TextField(
          controller: myController,
        ),
        RaisedButton(
          child: Text('Clear Text'),
          onPressed: (){
            myController.clear();
          },
        ),]
      ),
      ),
      ),   
    );
  }
}

Following is the output of this example.

I hope this tutorial will be helpful for you. Stay tuned for more tutorials.

Leave a Comment

Your email address will not be published. Required fields are marked *