Flutter Clear Search Text Persists Search

1.1k views Asked by At

I have a Text Field with _searchController and a separate IconButton that clears the _searchController: enter image description here

_placesList are the search results.

I also have a method _onSearchChanged that is a listener for the _searchController: enter image description here

The _onSearchChanged method calls another method that makes an API call if the search controller is not empty: enter image description here

When the cancel icon button is pressed, I found (through debugging) that the search controller listener is triggered before the search controller text is cleared and therefore an API call is made and THEN the search controller text is actually cleared.

This leaves a list of unwanted search results on the screen.

Hitting the cancel icon button a 2nd time results in the desired outcome of clearing the search results. But obviously I don't want the user to have to press the cancel icon button twice.

I want the cancel icon button to clear the search text and the search results.

1

There are 1 answers

2
Max Mustermann On

I believe you are missing setState here. Simply wrap the _searchController.clear(); in it like tihs:

setState( () {_searchController.clear();} );

Otherwise flutter won't rebuild with the new data. This is a common mistake that people forget about.