简体   繁体   中英

Flutter Clear Search Text Persists Search

I have a Text Field with _searchController and a separate IconButton that clears the _searchController: 在此处输入图像描述

_placesList are the search results.

I also have a method _onSearchChanged that is a listener for the _searchController: 在此处输入图像描述

The _onSearchChanged method calls another method that makes an API call if the search controller is not empty: 在此处输入图像描述

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM