by @kodeazy
How to add clear button to input field in flutter?
- In this blog we will discuss on how to
clear
the text in input field by creating clear button. - To add clear button to input field in flutter we use
TextEditingController
class. -
Create the object as below.
var clearTextObject = TextEditingController();
-
Now add the created object
clearTextObject
ascontroller
inside theTextField
widget as below syntax.TextField( controller: clearTextObject, decoration: InputDecoration( labelText: 'Password', suffixIcon: IconButton( onPressed: clearTextObject.clear, icon: Icon(Icons.clear_sharp), )))
-
Below is the sample example of creating a clear button
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { var _clearTextObject = TextEditingController(); @override Widget build(BuildContext context) { return MaterialApp( title: 'kodeazy', home: Scaffold( appBar: AppBar( title: Text("Input Field Clear Button Example"), ), body: Column( children: [ Text("Password"), TextField( controller: _clearTextObject, decoration: InputDecoration( labelText: 'Password', suffixIcon: IconButton( onPressed: _clearTextObject.clear, icon: Icon(Icons.clear_sharp), ))) ], ), ), ); } }
Output