How to create a search bar in Flutter

Flutter is a powerful toolkit, created by Google, to build fast mobile, web, and desktop applications using just one Codebase. It offers an easy-to-use and flexible development environment, making it a popular choice for developers to create beautiful and responsive user interfaces across multiple platforms.

Search bar

A search bar is a user interface element that allows users to provide text to search or filter content. It’s commonly used in applications where we have a list of items and want to search and find specific items within that list quickly.

Create a search bar in Flutter

Let’s follow the steps below to create a search bar in the Flutter application:

1- Create a Flutter project

Let’s start by creating a new Flutter project. For this, open the terminal and execute the following commands:

flutter create searchbar
cd searchbar

2- Create the user interface

We’ll create a TextField for the search bar, which will be controlled by a TextEditingConroller named _searchController. This can be implemented using the following code:

// Search bar controller
TextEditingController _searchController = TextEditingController();
// UI for the search bar
Container(
padding: EdgeInsets.symmetric(horizontal: 16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: Colors.grey[300],
),
child: Row(
children: [
Icon(Icons.search),
SizedBox(width: 10),
Expanded(
child: TextField(
controller: _searchController,
onChanged: (_) => {_filterItems(_searchController.text)},
decoration: InputDecoration(
hintText: 'Search...',
border: InputBorder.none,
),
),
),
],
),
)

3- Implementation of search bar

We’ll create a list of names in the application using the following code:

 List<String> names = [
  'John',
  'James',
  'Williams',
  'Sarah',
  'Sarmeen',
  'Thomas',
  'Alex'
  ];

Next, we create a list of filtered names which will change when the text in the search bar changes. At the start of the application, it will be initialized with the list of all names.

List<String> _filteredItems = [];

  void initState() {
    // TODO: implement initState
    super.initState();
    _filteredItems.addAll(names);
  }

Now, we will display the filtered list using ListView.builder, which is given in the code below:

ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: _filteredItems.length,
itemBuilder: (context, index) {
return Container(
margin: EdgeInsets.all(20),
color: Colors.green.withOpacity(0.2),
height: 100,
width: 100,
child: Center(
child: Text(_filteredItems[index])
)
)
)

We will create a function that changes the filtered list according to the text in the search bar.

// Function to filter items according to the text in search bar
void _filterItems(String query) {
setState(() {
_filteredItems = names
.where((item) => item.toLowerCase().contains(query.toLowerCase()))
.toList();
});
}

Example

Let’s look at an example showing the complete implementation of the search bar in the Flutter application.

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "Launch Chrome against localhost",
            "url": "http://localhost:8080",
            "webRoot": "${workspaceFolder}"
        }
    ]
}

Note: You can find your application running at the given link once you run the code widget above.

Explanation

  • Lines 51–57: We use of a search bar to filter the names from the list of all the names, names.

  • Lines 86–91: We create the search bar using the TextField, which is controlled by the controller _searchController.

  • Lines 88–111: We create a _filterItems function that takes query as a parameter and updates the _filteredItems list according to the text in the search bar. This _filteredItems list is then displayed under the search bar which is updated whenever the text in the search bar changes.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved