Flutter expand from icon to search bar but without suggestions area

  Kiến thức lập trình

Flutter documentation describes two useful material3 widgets SearchBar (which provides a full-row search bar, that is like a text input) and SearchAnchor (which provides a search view and suggestions area; can be used both with SearchBar and standalone – for example, a simple icon, when clicked – opens the search view).

I am trying to achieve the latter behavior but with a twist: I want a search icon (for context, I want to put this icon to the app bar); when clicked – it expands to a standard search bar (but not full screen, showSearch() is not viable ) and it must not have suggestions area. Is this possible using these widgets?

Something like this:

Before click – only icons is visible

After click – searchbar expanded, no suggestions

My workaround right now is just providing viewConstraints for SearchAnchor with no enough space for suggestions area – but this is very bad (see the second screenshot for how it looks – divider line is still visible).

return SearchAnchor(
        viewConstraints:
            BoxConstraints(minWidth: 550.0, minHeight: 0, maxHeight: 58),
        isFullScreen: false,
        searchController: _controller,
        viewHintText: "hint",
        textInputAction: TextInputAction.search,
        keyboardType: TextInputType.numberWithOptions(),
        builder: (BuildContext context, SearchController controller) {
          return IconButton(
            icon: const Icon(Icons.search),
            onPressed: () {
              controller.openView();
            },
          );
        },
        viewOnSubmitted: (text) {
          _controller.closeView(text);
        },
        suggestionsBuilder:
            (BuildContext context, SearchController controller) {
          return List<ListTile>.empty();
        });

Any help is appreciated.

New contributor

Caffadras is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT