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 check out my blog post how to add text input in flutter.
In this flutter tutorial, we make use of the TextField controller and its method clear. There’s a TextField and an ElevatedButton. When the ElevatedButton is pressed the TextField gets cleared.
See the following code snippet.
TextField(
controller: _controller,
onSubmitted: (String value) {
debugPrint(value);
},
),
ElevatedButton(
child: const Text('Clear Text'),
onPressed: () {
_controller.clear();
},
),
Then you will get the following output.
Following is the complete code for reference.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter TextField Clear'),
),
body: const MyStatefulWidget());
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
late TextEditingController _controller;
@override
void initState() {
super.initState();
_controller = TextEditingController();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Center(
child: Column(children: <Widget>[
TextField(
controller: _controller,
onSubmitted: (String value) {
debugPrint(value);
},
),
ElevatedButton(
child: const Text('Clear Text'),
onPressed: () {
_controller.clear();
},
),
]),
)));
}
}
I hope this tutorial to clear TextField in Flutter is helpful for you. Stay tuned for more tutorials.