How to Clear Entered Text from TextField in Flutter

In this example, we are going to show you how to clear entered text from TextField or TextFormField programmatically or button click in Flutter. See the example below:

Declare controller for TextField or TextFormField:

TextEditingController textarea = TextEditingController();

Set controller on TextField or TextFormField:

TextField(
  controller: textarea
)

Clear Text from TextField:

textarea.clear();

OR

textarea.text = "";

import 'package:flutter/material.dart';

void main() {
  runApp( MaterialApp(
       home: Home()
  ));
}

class Home extends  StatefulWidget {
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {

  TextEditingController textarea = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
         appBar: AppBar(
            title: Text("Clear Text From TextField"),
            backgroundColor: Colors.deepPurpleAccent,
         ),
          body: Container(
             alignment: Alignment.center,
             padding: EdgeInsets.all(20),
             child: Column(
               children: [
                   TextField(
                      controller: textarea,
                      decoration: InputDecoration( 
                         hintText: "Enter Remarks",
                         focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(width: 1, color: Colors.redAccent)
                         )
                      ), 
                   ),

                   ElevatedButton(
                     onPressed: (){
                         textarea.clear();
                         //or use: 
                         //textarea.text = "";
                     }, 
                     child: Text("Clear Text from TextField")
                    )
               ],
             ),
          )
      );
  }
}

In this way, you can clear entered text from TextField or TextFormField in Flutter.

No any Comments on this Article


Please Wait...