Flutter is known for the flexibility it provides for a variety of applications, from e-commerce to education to banking apps, and more. All of this is accomplished through the use of widgets that act as simple building blocks for complex applications. You can break each application down into components, some of which are common to all applications, while others are specific.

This article is based on a more generic component used in a variety of applications: the search bar. The search bar is used to query an item of data in the database.

In this article, we will build a search bar from scratch, using the various properties provided by Flutter’s Container Widget and box decoration.

The application that contains the search bar will be a raw diary application. It will consist of a textField class that appears when the “search” icon is clicked and disappears when “Cancel” is clicked in the sample application.

Before we begin, please note that this article assumes that you have already set up the Flutter development environment and are familiar with the basics of Flutter components and development.

Set up a Flutter sample application

The first step is to create a new project using the Flutter create command.

flutter create search_bar

Copy the code

Next, we need to clear the contents of the main.dart file and create a new MaterialApp.

import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return const MaterialApp( debugShowCheckedModeBanner: false, title: 'Material App', home: HomeScreen(), ); }}Copy the code

We used Material Design in this application to make it easier to set up; Our main focus will be on creating the search bar, not designing the app itself.

Now let’s create a new stateful widget named HomeScreen and pass it to the Home page property of the MaterialApp.

class HomeScreen extends StatefulWidget { const HomeScreen({Key? key}) : super(key: key); @override _HomeScreenState createState() => _HomeScreenState(); } class _HomeScreenState extends State<HomeScreen> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('My Personal Journal'), automaticallyImplyLeading: false, centerTitle: true, ), body: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Center( child: Text('Hi'), ), ], ), ); }}Copy the code

You’ll notice that I added some details to the application in the code above, including an appBar and a title. Again, these are unimportant additions that we can ignore and focus on creating the search bar, but might come in handy if you practice your application building skills in this tutorial.

Create a search button

The next step is to create the search button. AppBar provides us with a property called Actions that we can use to list various activities.

 appBar: AppBar(
  title: const Text('My Personal Journal'),
  automaticallyImplyLeading: false,
  actions: [
   IconButton(
   onPressed: () {},
   icon: const Icon(Icons.search),
   )
  ],
  centerTitle: true,
  ),

Copy the code

Since we are making a button that displays something (the search bar) when it is clicked, we will use the IconButton widget. This widget, when pressed, produces a small animation indicating that the user’s choice is registered with the application. We pass the name to the icon parameter; As you can see in the image below, I chose the magnifying glass icon to represent “search”.

The following image depicts the current state of our application.

We need to implement onPressed to trigger state reconstruction to display the text field. We must also make the current magnifying glass search icon become a “cancel” icon when the text field is displayed. The Cancel button will be used to cancel the search operation, as its name suggests.

The next step is to create two variables in the HomeScreen Widget: the first is an icon and the second is a widget. They will hold the default search button and the title of the AppBar.

Instead of hard-coding like before, we’ll pass them into variables and then pass the variables wherever they’re needed.

 @override
 _HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
 Icon customIcon = const Icon(Icons.search);
 Widget customSearchBar = const Text('My Personal Journal');
 @override
 Widget build(BuildContext context) {
 return Scaffold(
  appBar: AppBar(
  title: customSearchBar,
  automaticallyImplyLeading: false,
  actions: [
   IconButton(
   onPressed: () {},
   icon: customIcon,
   )
  ],
  centerTitle: true,
  ),

Copy the code

Manage state

Because we want the text field in the app bar to display when the search button is pressed, we have to update the status of the app. In this article, we will use the setState({}) function to update the state.

In the IconButton onPressed function, we call the setState function to update the state of our previously declared variables (that is, the customIcon variable and the customSearchBar variable).

We then run an if-else condition to check the current icon and make the correct decision.

onPressed: () { setState(() { if (customIcon.icon == Icons.search) { // Perform set of instructions. } else { customIcon = const Icon(Icons.search); customSearchBar = const Text('My Personal Journal'); }}); },Copy the code

Currently, it checks if customIcon is a searchIcon and then executes some instructions based on the result. If it’s not a search icon, it updates the variables to their defaults/ Original values.

if (customIcon.icon == Icons.search) { customIcon = const Icon(Icons.cancel); customSearchBar = const ListTile( leading: Icon( Icons.search, color: Colors.white, size: 28, ), title: TextField( decoration: InputDecoration( hintText: 'type in journal name... ', hintStyle: TextStyle( color: Colors.white, fontSize: 18, fontStyle: FontStyle.italic, ), border: InputBorder.none, ), style: TextStyle( color: Colors.white, ), ), ); }Copy the code

Inside the if-else logical block, we pass in the new status value we want to call: customIcon is assigned to the cancel Icon (icon.cancel), and customSearchBar is assigned to the ListTile containing the TextField.

In the code above, the search icon is passed to the application’s main parameter, and the TextField is given the Title widget. HintText and styles are adjusted through the InputDecoration widget, while InputBorder is removed through the InputBorder. None property.

Finally, our search bar is fully implemented!

conclusion

Regardless of the type of application, there are some components common to Flutter applications. One of them is the search bar. Querying a database for a particular piece of information is a tool that many mobile applications need. By learning this article, you can now create and customize the search bar in your Flutter application.

The postHow to create a search bar in Flutterappeared first onLogRocket Blog.