I’m trying to build a search field with a clear button who appear when i type some text in. But i tried a ternary condition to display my button, it never appear.
Thanks in advance
Here is my class:
`class SearchField extends StatefulWidget {
@override
_SearchFieldState createState() => _SearchFieldState();
}
class _SearchFieldState extends State {
TextEditingController _controller = TextEditingController();
@override
Widget build(BuildContext context) {
return TextField(
controller: _controller,
style: const TextStyle(
color: Colors.white,
),
decoration: InputDecoration(
labelText: 'Search',
labelStyle: TextStyle(
color: Color.fromARGB(255, 255, 255, 255).withOpacity(0.4),
fontFamily: 'Inter',
),
border: InputBorder.none,
suffixIcon: _controller.text.isEmpty //my clear button
? null
: IconButton(
icon: Icon(Icons.clear),
onPressed: () {
setState(() {
_controller.clear();
});
},
)
),
onEditingComplete: () {
// TODO: search contact with _controller.text
FocusScope.of(context).unfocus();
},
);
}
}`
2
Answers
I found the answer just after asking the question:
I had to add onChanged on my text like this and it's work:
This can help you, I only added a new field to handler field empty state, and on the
TextField
I used onChanged to update the previous var, and updated the clear method to return to the initial value