How to Create Toolbar SearchView In Flutter?

· 5 min read
How to Create Toolbar SearchView In Flutter?

When a user displays data in a ListView Widget it has a large amount of data. So, in this article, We will go through how to Create Toolbar SearchView In Flutter.

How to Create Toolbar SearchView In Flutter?

When a user displays data in a ListView Widget it has a large amount of data. So, to improve performance users need to implement search Properties where users can search an Item from available items. You should use SearchDelegate which comes out of the box with Flutter. Consider a code snippet as below:

class SearchPage extends StatefulWidget {
  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  String _result;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Search")),
      body: Center(
        child: Column(
          children: <Widget>[
            Text(_result ?? "", style: TextStyle(fontSize: 18)),
            RaisedButton(
              onPressed: () async {
                var result = await showSearch<String>(
                  context: context,
                  delegate: CustomDelegate(),
                );
                setState(() {
                  _result = result;
                });
              },
              child: Text("Search"),
            ),
          ],
        ),
      ),
    );
  }
}

class CustomDelegate<T> extends SearchDelegate<T> {
  List<String> data = nouns.take(100).toList();

  @override
  List<Widget> buildActions(BuildContext context) => [IconButton(icon: Icon(Icons.clear), onPressed: () => query = '')];

  @override
  Widget buildLeading(BuildContext context) => IconButton(icon: Icon(Icons.chevron_left), onPressed: () => close(context, null));

  @override
  Widget buildResults(BuildContext context) => Container();

  @override
  Widget buildSuggestions(BuildContext context) {
    var listToShow;
    if (query.isNotEmpty)
      listToShow = data.where((e) => e.contains(query) && e.startsWith(query)).toList();
    else
      listToShow = data;

    return ListView.builder(
      itemCount: listToShow.length,
      itemBuilder: (_, i) {
        var noun = listToShow[i];
        return ListTile(
          title: Text(noun),
          onTap: () => close(context, noun),
        );
      },
    );
  }
}

We will get output like below. In the output, you can see there is a search bar. You can search for the input provided in the code.

Search Toolbar In Flutter
Search Toolbar In Flutter

You can do this by editing the leading, title, and actions of AppBar.

appBar: new AppBar(
    leading: _isSearching ? const BackButton() : null,
    title: _isSearching ? _buildSearchField() : _buildTitle(context),
    actions: _buildActions(),
 ),

There’s also the Flutter flutter_search_view_pk library you could use to implement the same sort of design that Youtube/Instagram uses.

How to integrate and use?

So, first, directly drag and drop the pk_search_bar directory into your Flutter project. After that create a Class SearchScreen and in build > Scaffold > child: SearchBar().

Navigator.push(
  context,
  MaterialPageRoute(
      builder: (context) =>  SearchScreen()),
);

Consider a code snippet like below:

Widget searchBar(BuildContext context) {
   return SearchBar<CountryModel>(
   searchBarPadding: EdgeInsets.only(left: 5, right: 5, top: 10, bottom: 5),
   headerPadding: EdgeInsets.only(left: 0, right: 0),
   listPadding: EdgeInsets.only(left: 0, right: 0),
   hintText: "Search Placeholder",
   hintStyle: TextStyle(
    color: Colors.black54,
  ),
  textStyle: TextStyle(
    color: Colors.black,
    fontWeight: FontWeight.normal,
  ),
  iconActiveColor: Colors.deepPurple,
  shrinkWrap: true,
  mainAxisSpacing: 5,
  crossAxisSpacing: 5,
  suggestions: widget.countryModelList,
  cancellationWidget: Text("Cancel"),
  minimumChars: 1,
  emptyWidget: Center(
    child: Padding(
      padding: const EdgeInsets.only(left: 10, right: 10),
      child: Text("There is no any data found"),
    ),
  ),
  onError: (error) {
    return Center(
      child: Padding(
        padding: const EdgeInsets.only(left: 10, right: 10),
        child: Text("$error", textAlign: TextAlign.center),
      ),
    );
  },
  loader: Center(
    child: LoadingIndicator(),
  ),
  onSearch: getCountrySearchWithSuggestion, /// CountrySearch  // if 
   want to search with API then use thi ----> getCountryListFromApi
  onCancelled: () {
    Navigator.pop(context);
  },
  buildSuggestion: (CountryModel countryModel, int index) {
    return countryGenerateColumn(countryModel, index);
  },
  onItemFound: (CountryModel countryModel, int index) {
    return countryGenerateColumn(countryModel, index);
  },
);
}

The above code will give us output like below. You can see there are various countries on the list. On clicking the search option you will see a search bar. There you can type the name of the country which you want to find.

Search ToolBar new
Search ToolBar new

Conclusion:

Thanks for being with us on a Flutter Journey!

So, in this article, we have seen how to Create Toolbar SearchView In Flutter.  Also, feel free to comment and provide any other suggestions regarding Flutter.

Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. Also, the portal is full of cool resources from Flutter like Flutter Widget GuideFlutter Projects, Code libs and etc.

Flutter Agency is one of the most popular online portals dedicated to Flutter Technology. Daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Leave a Reply