The search bar is a basic UI element provided by each and every application or website we use to search for the content we need. The basic search bar can be created easily but the one we are going to make will search for elements based on an entered substring in real-time. Let's see how to create the search bar.
Step by Step Implementation
Step 1: Create a new Flutter Application
Create a new Flutter application using the command Prompt. To create a new app, write the following command and run it.
flutter create app_name
To know more about it refer this article: Creating a Simple Application in Flutter
Step 2: Working with main.dart
After creating the project, open the main.dart file.
Dart
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This is the root widget
// of your application
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: GFG(),
);
}
}
Step 3: Create a Stateful Class
Below the MyApp widget creates a stateful widget and name it as you wish. In VS Code you can try typing stf and the autocomplete will give you a stateful widget as the suggestion select it and name it just like shown in the code below.
Dart
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: GFG(),
);
}
}
// This is the widget that will be shown
// as the homepage of your application.
class GFG extends StatefulWidget {
const GFG({Key? key}) : super(key: key);
@override
State<GFG> createState() => _GFGState();
}
class _GFGState extends State<GFG> {
@override
Widget build(BuildContext context) {
return Scaffold();
}
}
Step 4: Develop AppBar
Now, in Scaffold use the parameter appBar and use appBar's actions parameter to create an IconButton inside it.
Dart
class GFG extends StatefulWidget {
const GFG({Key? key}) : super(key: key);
@override
State<GFG> createState() => _GFGState();
}
class _GFGState extends State<GFG> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
"GeeksForGeeks",
),
actions: [
IconButton(
onPressed: () {
// method to show the search bar
showSearch(
context: context,
// delegate to customize the search bar
delegate: CustomSearchDelegate()
);
},
icon: const Icon(Icons.search),
)
],
),
);
}
}
Step 5: Create CustomSearchDelegate
Creating the CustomSearchDelegate class which extends SearchDelegate. The SearchDelegate has 4 necessary overrides that need to be implemented.
Dart
class CustomSearchDelegate extends SearchDelegate {
// Demo list to show querying
List<String> searchTerms = [
"Apple",
"Banana",
"Mango",
"Pear",
"Watermelons",
"Blueberries",
"Pineapples",
"Strawberries"
];
// First overwrite to clear the search text
@override
List<Widget>? buildActions(BuildContext context) {
return [
IconButton(
onPressed: () {
query = '';
},
icon: Icon(Icons.clear),
),
];
}
// Second overwrite to pop out of search menu
@override
Widget? buildLeading(BuildContext context) {
return IconButton(
onPressed: () {
close(context, null);
},
icon: Icon(Icons.arrow_back),
);
}
// Third overwrite to show query result
@override
Widget buildResults(BuildContext context) {
List<String> matchQuery = [];
for (var fruit in searchTerms) {
if (fruit.toLowerCase().contains(query.toLowerCase())) {
matchQuery.add(fruit);
}
}
return ListView.builder(
itemCount: matchQuery.length,
itemBuilder: (context, index) {
var result = matchQuery[index];
return ListTile(
title: Text(result),
);
},
);
}
// Last overwrite to show the querying
// process at the runtime
@override
Widget buildSuggestions(BuildContext context) {
List<String> matchQuery = [];
for (var fruit in searchTerms) {
if (fruit.toLowerCase().contains(query.toLowerCase())) {
matchQuery.add(fruit);
}
}
return ListView.builder(
itemCount: matchQuery.length,
itemBuilder: (context, index) {
var result = matchQuery[index];
return ListTile(
title: Text(result),
);
},
);
}
}
With this, we have created our search bar.
Final CustomSearchDelegate code:
Dart
class CustomSearchDelegate extends SearchDelegate {
// Demo list to show querying
List<String> searchTerms = [
"Apple",
"Banana",
"Mango",
"Pear",
"Watermelons",
"Blueberries",
"Pineapples",
"Strawberries"
];
// First overwrite to clear the search text
@override
List<Widget>? buildActions(BuildContext context) {
return [
IconButton(
onPressed: () {
query = '';
},
icon: Icon(Icons.clear),
),
];
}
// Second overwrite to pop out of search menu
@override
Widget? buildLeading(BuildContext context) {
return IconButton(
onPressed: () {
close(context, null);
},
icon: Icon(Icons.arrow_back),
);
}
// Third overwrite to show query result
@override
Widget buildResults(BuildContext context) {
List<String> matchQuery = [];
for (var fruit in searchTerms) {
if (fruit.toLowerCase().contains(query.toLowerCase())) {
matchQuery.add(fruit);
}
}
return ListView.builder(
itemCount: matchQuery.length,
itemBuilder: (context, index) {
var result = matchQuery[index];
return ListTile(
title: Text(result),
);
},
);
}
// Last overwrite to show the querying
// process at the runtime
@override
Widget buildSuggestions(BuildContext context) {
List<String> matchQuery = [];
for (var fruit in searchTerms) {
if (fruit.toLowerCase().contains(query.toLowerCase())) {
matchQuery.add(fruit);
}
}
return ListView.builder(
itemCount: matchQuery.length,
itemBuilder: (context, index) {
var result = matchQuery[index];
return ListTile(
title: Text(result),
);
},
);
}
}
Complete Source Code
main.dart:
Dart
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This is the root widget of your application
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(primarySwatch: Colors.blue),
home: GFG(),
);
}
}
class GFG extends StatefulWidget {
const GFG({Key? key}) : super(key: key);
@override
State<GFG> createState() => _GFGState();
}
class _GFGState extends State<GFG> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("GeeksForGeeks"),
actions: [
IconButton(
onPressed: () {
// Method to show the search bar
showSearch(
context: context,
// Delegate to customize the search bar
delegate: CustomSearchDelegate(),
);
},
icon: const Icon(Icons.search),
),
],
),
);
}
}
class CustomSearchDelegate extends SearchDelegate {
// Demo list to show querying
List<String> searchTerms = [
"Apple",
"Banana",
"Mango",
"Pear",
"Watermelons",
"Blueberries",
"Pineapples",
"Strawberries",
];
// First overwrite to clear the search text
@override
List<Widget>? buildActions(BuildContext context) {
return [
IconButton(
onPressed: () {
query = '';
},
icon: Icon(Icons.clear),
),
];
}
// Second overwrite to pop out of search menu
@override
Widget? buildLeading(BuildContext context) {
return IconButton(
onPressed: () {
close(context, null);
},
icon: Icon(Icons.arrow_back),
);
}
// Third overwrite to show query result
@override
Widget buildResults(BuildContext context) {
List<String> matchQuery = [];
for (var fruit in searchTerms) {
if (fruit.toLowerCase().contains(query.toLowerCase())) {
matchQuery.add(fruit);
}
}
return ListView.builder(
itemCount: matchQuery.length,
itemBuilder: (context, index) {
var result = matchQuery[index];
return ListTile(title: Text(result));
},
);
}
// Last overwrite to show the querying
// process at the runtime
@override
Widget buildSuggestions(BuildContext context) {
List<String> matchQuery = [];
for (var fruit in searchTerms) {
if (fruit.toLowerCase().contains(query.toLowerCase())) {
matchQuery.add(fruit);
}
}
return ListView.builder(
itemCount: matchQuery.length,
itemBuilder: (context, index) {
var result = matchQuery[index];
return ListTile(title: Text(result));
},
);
}
}
Output:
a
Similar Reads
Flutter Bloc - Basic Search
In this article, we are going to develop a Basic Search App using Flutter Bloc and Clean Architecture. In Flutter applications, the Flutter BLoC (Business Logic Component) is used to manage the state. It helps separate business logic from UI. It ensures that the user interface is not strongly liaiso
15+ min read
Flutter - Tab Bar
In this article, we see the Tab bar in Flutter. Tab Bar is mostly used in applications. So we will see how we can create the tab bar in flutter just because nowadays companies demand the flutter app the most. Tab Bar generally handle with the controller and in Flutter, there are many controllers lik
4 min read
Flutter - Build Hotel Search App
The world of mobile applications has seen a tremendous surge in the travel and tourism sector. In this tutorial, we will explore how to develop a hotel search app using Flutter, a powerful cross-platform framework. Flutter provides a rich set of tools and widgets for crafting engaging and performant
8 min read
Flutter - AppBar Widget
AppBar is usually the topmost component of the app (or sometimes the bottom-most), it contains the toolbar and some other common action buttons. As all the components in a Flutter application are a widget or a combination of widgets. So AppBar is also a built-in class or widget in Flutter which give
7 min read
Flutter - Collapse Sidebar
Sidebar is also called the Drawer of the Application and mainly use in every android and iOS Application. Sidebar is used to work with more screens and make the application more user interactive. Sidebar provides the users to use the different screens in the single-page application. A collapsible si
4 min read
Flutter - Hide the Status Bar
StatusBar is located at the top of the Application, which basically shows the notification of the phones. Sample images are given below to get an idea about what we are going to do in this article. Before Hiding the status bar: Â After Hiding the status bar: Â If you see the difference between the i
2 min read
Flutter - Shimmer
In Flutter, Shimmer is used to add beautiful animations while content is loading from the servers in an application. This makes the UI look more responsive and secures users from leaving a slow internet interaction. It can be used instead of conventional ProgressBar or usual loaders available in the
4 min read
Flutter - Banner Widget
Banner widget comes built-in with flutter API. It is somewhat similar to the debug banner that we are used to seeing on the top-right corner on a flutter app in debug mode. It enables us to show a message or text on top of any other widget. Below we will see its implementation with the help of an ex
3 min read
Flutter - Dark Theme
Nowadays almost all the mobile application uses a dark theme, for example, Instagram, Whatsapp, Youtube, etc. Itâs easy to implement in Flutter, Just a few lines of code require to achieve this. But before doing that letâs explore some important concept in flutter which are used to achieve the dark
4 min read
Flutter - Custom Tab Bar
In this article, we will see about the Custom Tab Ba, and also how you can create the tab bar inside the tab bar. Making the tab bar is very easy you just go and return the default controller and give the length and Make the tab bar, But In this article, we will see how you can create the tab bar an
5 min read