0

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 Answers1

0

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.

  • Thanks, but I have tried variations of this to no effect. When the clear() is called it seems like it puts the listener function in a stack, then clears the text, then puts the another listener function with the text cleared into the stack. Then it runs the stack. Therefore the function before the text is cleared is ran last. Leaving the page with any empty search text but a list of results. – canislupus8 Dec 06 '20 at 01:02
  • I could not reproduce this issue .I think there also might be a problem with the `selectedEntry` that you compare to the `controller.text`. It may still hold the old value and therefore you dont enter the if branch. Try setting it to an empty string before you call `clear()`. – Max Mustermann Dec 06 '20 at 11:05