Search code examples
searchflutterappbar

Place text box in appbar in Flutter


I want to implement an Appbar like below where there are a textbox and multiple icons:

appbar layout

The icons can be added in action easily, but how to add the text box and add search action to it. There are many search bar plugins available, but all of them occupy the whole app bar and no way to mention the hints. Can anyone give some idea, it will be a great help for me.


Solution

  • In the title propiery, inside the AppBar, you can pass a widget, which means you can add any component you want, like a TextField. see the example below:

    appBar: AppBar(
            title: TextField(
              decoration: InputDecoration(
                hintText: 'Search',
                prefixIcon: Icon(Icons.search)
              ),
            ),
          ),
    

    I suggest to you, to wrap this TextField in a GestureDetector, disable the TextField with the proprierty called enable (set to false), and in the onTap method inside the GestureDetector, you can call a showSearch() method.

    To call this showSearch(), you'll need to pass a context and a searchDelegate which is a component that extends a class, check this example:

    class CustomSearchDelegate extends SearchDelegate {
      @override
      List<Widget> buildActions(BuildContext context) {
        // TODO: implement buildActions
        return null;
      }
    
      @override
      Widget buildLeading(BuildContext context) {
        // TODO: implement buildLeading
        return null;
      }
    
      @override
      Widget buildResults(BuildContext context) {
        // TODO: implement buildResults
        return null;
      }
    
      @override
      Widget buildSuggestions(BuildContext context) {
        // TODO: implement buildSuggestions
        return null;
      }
    }
    

    Source: Implementing search in Flutter

    Now, you can do this:

    GestureDetector:
      onTap: () => showSearch(context: context, delegate: CustomSearchScreen()),
      child: ....