Reputation: 113
My aim is to build a search box using TextField which have a icon button in the end of the field to clear out what is in the text field. Currently I'm using,
TextField(
controller: _searchFieldController,
decoration: InputDecoration(
filled: true,
fillColor: Colors.white,
prefixIcon: Icon(Icons.search),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0)),
hintText: 'Search here...',
hintStyle: Theme.of(context).textTheme.caption,
suffixIcon: _searchFieldController.text.length > 0 ? IconButton(
onPressed: () {
_searchFieldController.clear();
},
icon: Icon(Icons.cancel, color: Colors.grey)
) : null,
),
),
with following text editing controller.
final _searchFieldController = TextEditingController();
_searchFieldController.addListener(() {
print(_searchFieldController.text.length);
});
But the suffixIcon never appears. Can anyone tell how to get this right?
Upvotes: 1
Views: 1355
Reputation: 279
You can try to implementing suffixIcon property to solve your this error.
TextFormField(
suffixIcon: const Icon(Icons.person),
onChanged: (value) {},
hintText: ConstString.firstName,
validator: (value) {
if (value!.isEmpty) {
return ConstString.enterFirstName;
} else {
return null;
}
},
controller: _firstName,
),
Upvotes: 0
Reputation: 21
simply put the setState((){})
in onChange like
onChange: (value) {
setState(() {});
},
Upvotes: 0
Reputation: 774
ValueListenableBuilder can listen to textEditingControllers. So we can have an implementation like this:
Define suffixIcon
inside your build method of the the widget.
final suffixIcon = ValueListenableBuilder(
valueListenable: controller,
builder: (_, value, ___) {
if (value.text.isNotEmpty) {
return IconButton(
onPressed: () => controller.clear(),
icon: const Icon(
Icons.cancel,
color: Colors.black,
),
);
} else {
return const SizedBox.shrink();
}
},
);
Use it inside the TextField
decoration:
TextField(
controller: controller,
decoration: InputDecoration(
suffixIcon:suffixIcon,
.....
Upvotes: 2
Reputation: 136
Try having a state variable for length and inside add listener function set the length and check the length for the icon visibility
final _searchFieldController = TextEditingController();
final _length = 0;
_searchFieldController.addListener(() {
setState(() => _length = _searchFieldController.text.length);
});
then check the _length variable
suffixIcon: _length > 0 ? IconButton(
onPressed: () {
_searchFieldController.clear();
},
icon: Icon(Icons.cancel, color: Colors.grey)
) : null
Upvotes: 2