Flutter – Search BarHow to create a Search Bar in Flutter with examples

One of the most fundamental user interface elements that every programme or website offers is a search bar, which we utilise to get the content we need. While it is simple to develop a basic search bar, the one we are going to create will search in real time for components based on a substring that is entered. Let’s look at how the search bar is made.

What is a search bar?

An feature of the user interface called a search bar enables the user to type a query and submit it to search a database or other information source. Web browsers, search engines, and app store apps all frequently have search bars that users may utilise to locate particular material or information.

A text area for the user to type their search query plus a button or icon to submit it make up a typical search bar. Additional features like autocomplete recommendations, filters, or recent searches are also included in certain search boxes.

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: Creating a Flutter project.

  • Launch Visual Studio coding and choose “Flutter: New Project” by pressing “Ctrl+Shift+P.”
  • Choose the folder where your application will be created.
  • Next, give your application a name.
  • Flutter SDK will start a new project for you when you hit “Enter.”

Step 2: After creating the project, open the main.dart file.

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: HomePage(),
	);
}
}
Dart

Step 3:

Make a stateful widget beneath the MyApp widget and give it whatever name you like. Try typing stf into VS Code, and the autocomplete feature will offer a stateful widget for you to select and name, precisely like the code below illustrates.

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: HomeScreen(),
	);
}
}

// This is the widget that will be shown
// as the homepage of your application.
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);

@override
State<HomeScreen> createState() => HomeScreenState();
}

class HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
	return Scaffold();
}
}
Dart

Step 4:

Now in Scaffold use the parameter appBar and use appBar’s actions parameter to create an IconButton inside it.

class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);

@override
State<HomeScreen> createState() =>HomeScreenState();
}

class HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
	return Scaffold(
	appBar: AppBar(
		title: const Text(
		"Search",
		),
		actions: [
		IconButton(
			onPressed: () {
			// method to show the search bar
			showSearch(
				context: context, 
				// delegate to customize the search bar
				delegate: MySearchBar()
			);
			},
			icon: const Icon(Icons.search),
		)
		],
	),
	);
}
}
Dart

Step 5: 

Creating the MySearchBar class which extends SearchDelegate. The SearchDelegate has 4 necessary overrides which need to be implemented.

class MySearchBar extends SearchDelegate {
  List<String> searchResults = ["India", "China", "USA", "Russia"];
  @override
  List<Widget>? buildActions(BuildContext context) {
    return [
      IconButton(
        onPressed: () {
          if (query.isEmpty) {
            close(context, null);
          } else {
            query = '';
          }
        },
        icon: Icon(Icons.clear),
      )
    ];
  }

  @override
  Widget? buildLeading(BuildContext context) {
    return IconButton(
        onPressed: () => close(context, null), icon: Icon(Icons.arrow_back));
  }

  @override
  Widget buildResults(BuildContext context) {
    return Center(
      child: Text(query),
    );
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    List<String> suggestions = searchResults.where((searchResultElement) {
      final result1 = searchResultElement.toLowerCase();
      final input = query.toLowerCase();
      return result1.contains(input);
    }).toList();

    return ListView.builder(
      itemCount: suggestions.length,
      itemBuilder: (BuildContext context, int index) {
        final suggesyionValue = suggestions[index];
        return ListTile(
          onTap: () {
            query = suggesyionValue;
            showResults(context);
          },
          title: Text(suggesyionValue),
        );
      },
    );
  }
}
Dart

Complete Dart code:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blue,
        title: const Text('Search bar'),
        actions: [
          IconButton(
              onPressed: () {
                showSearch(context: context, delegate: MySearchBar());
              },
              icon: const Icon(Icons.search))
        ],
      ),
    );
  }
}

class MySearchBar extends SearchDelegate {
  List<String> searchResults = ["India", "China", "USA", "Russia"];
  @override
  List<Widget>? buildActions(BuildContext context) {
    return [
      IconButton(
        onPressed: () {
          if (query.isEmpty) {
            close(context, null);
          } else {
            query = '';
          }
        },
        icon: Icon(Icons.clear),
      )
    ];
  }

  @override
  Widget? buildLeading(BuildContext context) {
    return IconButton(
        onPressed: () => close(context, null), icon: Icon(Icons.arrow_back));
  }

  @override
  Widget buildResults(BuildContext context) {
    return Center(
      child: Text(query),
    );
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    List<String> suggestions = searchResults.where((searchResultElement) {
      final result1 = searchResultElement.toLowerCase();
      final input = query.toLowerCase();
      return result1.contains(input);
    }).toList();

    return ListView.builder(
      itemCount: suggestions.length,
      itemBuilder: (BuildContext context, int index) {
        final suggesyionValue = suggestions[index];
        return ListTile(
          onTap: () {
            query = suggesyionValue;
            showResults(context);
          },
          title: Text(suggesyionValue),
        );
      },
    );
  }
}
Dart

1 thought on “Flutter – Search BarHow to create a Search Bar in Flutter with examples”

Comments are closed.