Flutter - Search Bar - Implementing Search action in AppBar

Hello Guys, Today we are going to learn about how to create SearchBar in flutter?

In this post i will show you display

  • List of countries and search for given word using SearchBar at the top of the application
  • How to create Suggestions list for the search 
  • How to add actions clear to reset SearchBar

 

Let's Start

Step 1: Create Flutter application

Step 2: Setup Search Delegate to implement Search AppBar

SearchDelegate is where all magic happens. It contains two list of items. One list is for all countries which we are going to initialize first. Another list is _recentlist which contains recent search history.

class SearchBarDelegate  extends SearchDelegate
{

  List recentSuggest;
  SearchDelegate()
  {
     recentSuggest = ['Albania','Andorra'
    ];
  }
}

 

Step 3: After setting up country list in delegate, now its time to create an icon which will placed at top to left side of search bar fot Navigate to previous screen

class SearchBarDelegate  extends SearchDelegate
{
@override
    Widget buildLeading(BuildContext context) {
      return IconButton(
        tooltip: 'Back',
        icon: AnimatedIcon(
          icon: AnimatedIcons.menu_arrow,
          progress: transitionAnimation,
        ),
        onPressed: () {
          //Take control back to previous page
          this.close(context, null);
        },
      );
    }
}

 

Step 4:

Now its time to buildResults method to show searched items. This is where search query will display searched items

@override
  Widget buildResults(BuildContext context) {
    // TODO: implement buildResults
    return Center(child: Container(
      width: 100.0,
      height: 100.0,
      child: Card(
        color: Colors.redAccent,
        child: Center(
          child: Text(query),
        ),
      ),
    ),);;
  }

 

Step 5:

Next we are going to set suggestion list, First we will populate all countries when search bar query empty

@override
  Widget buildSuggestions(BuildContext context) {
    final suggestionList = query.isEmpty
        ? recentSuggest
        : countryList.where((input) => input.toUpperCase().startsWith(query.toUpperCase())).toList();
    return ListView.builder(
        itemCount: suggestionList.length,
        itemBuilder: (context, index) => ListTile(

          onTap: (){
            query = suggestionList[index];
            showResults(context);

            if(!recentSuggest.contains(query))
            recentSuggest.insert(0,query);
            },

          title: RichText(
              text: TextSpan(
                  text: suggestionList[index].substring(0, query.length),
                  style: TextStyle(
                      color: Colors.black, fontWeight: FontWeight.bold),
                  children: [
                    TextSpan(
                        text: suggestionList[index].substring(query.length),
                        style: TextStyle(color: Colors.grey))
                  ])),
        ));

 

Step 6:

Now set Actions to Search Delegate 

@override
  List buildActions(BuildContext context) {
    // TODO: implement buildActions
    return [IconButton(icon: Icon(Icons.clear), onPressed: () => query = "")];;
  }    

 

Step 7: Now add Search delegate to widget.

AppBar(
  backgroundColor: Colors.pink,
  title: Text("SearchBar"),
  actions: [
    IconButton(  icon: Icon(Icons.search), onPressed: (){
        showSearch(context: context, delegate: SearchBarDelegate(searchList));
    })
  ],

 

Step 8: Run the Application and check the result

 

Complete code

import 'package:flutter/material.dart';
import 'package:flutter_searchbar/contasnts.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.pink,
      ),
      home: SearchBar(),
    );
  }
}

class SearchBar extends StatefulWidget{
  @override
  State createState() {
    // TODO: implement createState
    return SearchBarState();
  }

}

class SearchBarState extends State
{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.pink,
          title: Text("SearchBar"),
          actions: [
            IconButton(  icon: Icon(Icons.search), onPressed: (){
                showSearch(context: context, delegate: SearchBarDelegate(searchList));
            })
          ],
        ),
        body:  Scrollbar(
      //Displaying all English words in list in app's main page
      child: ListView.builder(
      itemCount: searchList.length,
        itemBuilder: (context, idx) =>
            ListTile(
              title: Text(searchList[idx]),
              onTap: () {

              },
            ),
      ),
      ),
      ),
    );
  }

}

class SearchBarDelegate  extends SearchDelegate
{

  List recentSuggest;
  List countryList;
  SearchBarDelegate(_countryList)
  {
    countryList=_countryList;
     recentSuggest = ['Albania','Andorra' ];

  }
  @override
  List buildActions(BuildContext context) {
    // TODO: implement buildActions
    return [IconButton(icon: Icon(Icons.clear), onPressed: () => query = "")];;
  }

  @override
  Widget buildLeading(BuildContext context) {
    // TODO: implement buildLeading
    return IconButton(icon: AnimatedIcon(icon: AnimatedIcons.menu_arrow, progress: transitionAnimation), onPressed: (){
      close(context, null);
    });
  }

  @override
  Widget buildResults(BuildContext context) {
    // TODO: implement buildResults
    return Center(child: Container(
      width: 100.0,
      height: 100.0,
      child: Card(
        color: Colors.redAccent,
        child: Center(
          child: Text(query),
        ),
      ),
    ),);;
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    final suggestionList = query.isEmpty
        ? recentSuggest
        : countryList.where((input) => input.toUpperCase().startsWith(query.toUpperCase())).toList();
    return ListView.builder(
        itemCount: suggestionList.length,
        itemBuilder: (context, index) => ListTile(

          onTap: (){
            query = suggestionList[index];
            showResults(context);
            recentSuggest.insert(0,query);
            },

          title: RichText(
              text: TextSpan(
                  text: suggestionList[index].substring(0, query.length),
                  style: TextStyle(
                      color: Colors.black, fontWeight: FontWeight.bold),
                  children: [
                    TextSpan(
                        text: suggestionList[index].substring(query.length),
                        style: TextStyle(color: Colors.grey))
                  ])),
        ));;
  }

}




 


Subscribe For Daily Updates