How To Create Toolbar Searchview in Flutter

Share This Post

Many Flutter Developer have to implement searchview in toolbar of his App.How To Create Toolbar Searchview in Flutter. In this article, I will show you how to do the following:

Add a search bar within our AppBar along the top of the view in order to filter our ListView. It’s also easy to understand and will help implement search filter in flutter . This example also doesn’t require any setup or dependencies. This example will involve rendering a searchview in the toolbar or appBar of our application. Without Wasting Time Lets start This Article.

1.Make search_list.dart File

2. Add Imports.

Start by importing material.dart:

import 'package:flutter/material.dart';

3. Create Stateful Widget

Then create the widget by extending the StatefulWidget:

class SearchList extends StatefulWidget {

and defining the constructor:

  SearchList({ Key key }) : super(key: key);

then finally overriding the createState() method:

  @override
  _SearchListState createState() => new _SearchListState();
}

4. Create State Class

class _SearchListState extends State<SearchList>
{

Then define instance fields:

  Widget appBarTitle = new Text("Search Sample", style: new TextStyle(color: Colors.white),);
  Icon actionIcon = new Icon(Icons.search, color: Colors.white,);
  final key = new GlobalKey<ScaffoldState>();
  final TextEditingController _searchQuery = new TextEditingController();
  List<String> _list;
  bool _IsSearching;
  String _searchText = "";

In the constructor attach a listener to the TextEditingController

  _SearchListState() {
    _searchQuery.addListener(() {
      if (_searchQuery.text.isEmpty) {
        setState(() {
          _IsSearching = false;
          _searchText = "";
        });
      }
      else {
        setState(() {
          _IsSearching = true;
          _searchText = _searchQuery.text;
        });
      }
    });
  }

Now override the initState() method:

  @override
  void initState() {
    super.initState();
    _IsSearching = false;
    init();

  }

Then Add List of items to act as the data source:

  void init() {
    _list = List();
    _list.add("Google");
    _list.add("IOS");
    _list.add("Andorid");
    _list.add("Dart");
    _list.add("Flutter");
    _list.add("Python");
    _list.add("React");
    _list.add("Xamarin");
    _list.add("Kotlin");
    _list.add("Java");
    _list.add("RxAndroid");
  }

Override the build() method of this state class:

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      key: key,
      appBar: buildBar(context),
      body: new ListView(
        padding: new EdgeInsets.symmetric(vertical: 8.0),
        children: _IsSearching ? _buildSearchList() : _buildList(),
      ),
    );
  }

In it you can see we are building our widget by specifying the appBar as well as the body which in this case will contain a ListView.

Then two helper methods returning List of data:

  void init() {
    _list = List();
    _list.add("Google");
    _list.add("IOS");
    _list.add("Andorid");
    _list.add("Dart");
    _list.add("Flutter");
    _list.add("Python");
    _list.add("React");
    _list.add("Xamarin");
    _list.add("Kotlin");
    _list.add("Java");
    _list.add("RxAndroid");
  }

Override the build() method of this state class:

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      key: key,
      appBar: buildBar(context),
      body: new ListView(
        padding: new EdgeInsets.symmetric(vertical: 8.0),
        children: _IsSearching ? _buildSearchList() : _buildList(),
      ),
    );
  }

In it you can see we are building our widget by specifying the appBar as well as the body which in this case will contain a ListView.

Then two helper methods returning List of data:

  List<ChildItem> _buildList() {
    return _list.map((contact) => new ChildItem(contact)).toList();
  }

  List<ChildItem> _buildSearchList() {
    if (_searchText.isEmpty) {
      return _list.map((contact) => new ChildItem(contact))
          .toList();
    }
    else {
      List<String> _searchList = List();
      for (int i = 0; i < _list.length; i++) {
        String  name = _list.elementAt(i);
        if (name.toLowerCase().contains(_searchText.toLowerCase())) {
          _searchList.add(name);
        }
      }
      return _searchList.map((contact) => new ChildItem(contact))
          .toList();
    }
  }

Then a helper method to help in constructing the AppBar widget:

  Widget buildBar(BuildContext context) {
    return new AppBar(
        centerTitle: true,
        title: appBarTitle,
        actions: <Widget>[
          new IconButton(icon: actionIcon, onPressed: () {
            setState(() {
              if (this.actionIcon.icon == Icons.search) {
                this.actionIcon = new Icon(Icons.close, color: Colors.white,);
                this.appBarTitle = new TextField(
                  controller: _searchQuery,
                  style: new TextStyle(
                    color: Colors.white,

                  ),
                  decoration: new InputDecoration(
                      prefixIcon: new Icon(Icons.search, color: Colors.white),
                      hintText: "Search...",
                      hintStyle: new TextStyle(color: Colors.white)
                  ),
                );
                _handleSearchStart();
              }
              else {
                _handleSearchEnd();
              }
            });
          },),
        ]
    );
  }

That appBar widget will have a searchview in it as you can see in the above method.

Then lastly for this state class, create methods to handle search start and search end:

  void _handleSearchStart() {
    setState(() {
      _IsSearching = true;
    });
  }

  void _handleSearchEnd() {
    setState(() {
      this.actionIcon = new Icon(Icons.search, color: Colors.white,);
      this.appBarTitle =
      new Text("Search Sample", style: new TextStyle(color: Colors.white),);
      _IsSearching = false;
      _searchQuery.clear();
    });
  }

}

That is the end of the State class.

Also Read : How do I run code in the background, even with the screen off in Flutter?

Now below it create another class called childItem. It’s also a widget representing a single ListView item:

class ChildItem extends StatelessWidget {
  final String name;
  ChildItem(this.name);
  @override
  Widget build(BuildContext context) {
    return new ListTile(title: new Text(this.name));
  }

}

Main.dart File

Come in the main file and add the following code:

import 'package:flutter/material.dart';
import 'package:flutter_search_app/search_list.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Search',
      debugShowCheckedModeBanner: false,
      theme: new ThemeData(
        brightness: Brightness.light,
        primarySwatch:Colors.yellow,
        primaryColor: Color(0xFFFFBB54),
        accentColor: Color(0xFFECEFF1),
      ),
      home: new SearchList(),
    );
  }
}

This Code Demo:

Flutter SearchView Examples – ListView Search/Filter
Flutter SearchView Examples ListView

If You Still Not Understand Then Please Follow This Youtube Video.

So This Article Is About How To Create Toolbar Searchview in Flutter. Please Comment Below Your Thought About This Post. Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *

close