Reputation: 2690
I'm trying to do simple thing.. Displaying clear button when the TextField is not empty to clear the content and hide it when content is empty. Here is code
final TextEditingController _controller = TextEditingController();
...
TextFormField(
controller: _controller,
decoration: InputDecoration(
suffixIcon: _controller.text.length > 0
? IconButton(
icon: Icon(Icons.clear, size: 16),
onPressed: () {
_controller.clear();
},
)
: null))
This works but not with the keyboard activated. You have to close the keyboard to make it work.. How to do it live while typing with controller?
Upvotes: 2
Views: 1839
Reputation: 3548
Its because your UI is not rebuild until you close your keyboard which will trigger the rebuild, for this, you can use this little trick like this:
final TextEditingController controller = TextEditingController();
changesOnField() {
setState(() {}); // Will re-Trigger Build Method
}
@override
void initState() {
super.initState();
controller.addListener(changesOnField);
}```
Upvotes: 2
Reputation: 3469
You need to update the state every time the input changes:
TextEditingController _controller = TextEditingController();
@override
void initState() {
super.initState();
_controller.addListener(() {
setState(() {});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: TextFormField(
controller: _controller,
decoration: InputDecoration(
suffixIcon: _controller.text.isNotEmpty
? IconButton(
icon: Icon(Icons.clear, size: 16),
onPressed: () {
_controller.clear();
},
)
: null,
),
),
),
);
}
Upvotes: 7