Hey devs, today I'll show how to implement a search bar in flutter. This beautiful framework has tools to help us in this and other cases.
(Don't need any state management)
In this example, I going to implement a search field to open a text from a simple text list. The list will be generated.
- One Stateful widget
- One Scaffold
- One AppBar
- Data to be searched
No. I'll create a class that will manage our search mechanics. First of all, this is our basic struct:
What is the next step? Let's call the function
onPressed parament of
actions of the
AppBar. This function needs two paramete, the first is the context, just pass the BuildContext inherited of Scaffold. The second and the key to this implementation is the delegate, where I need to pass a SearchDelegate that I'll create now.
Now, let's create a class inherited from
SearchDelegate class and do an override of the four main methods.
The first method is
buildActions() that return a list of widgets. These widgets are on the right side of the text field. In this example, I'll create a single widget. It'll an IconButton that will clean up our query text.
For this, I created IconButton and on the icon parament I give her the close icon, and in onPressed, I just pass a
VoidCallback that will set the
query (the text of built-in
TextField()) to an empty string.
Now, let's implement the
buildLeading(). It's a single widget on the left of the search field. Usually, it's used the
arrow_back icon with
Navigator.pop() in the
The next method to be overridden is
buildResult(). It returns a widget that it'll cover the body of scaffold when the function
showResult() was called. In this simples example, I'll just display a
Container with a
Text in a
Center. For the text, I'll create a string that will receive the selected text.
The last method is
buildSuggestion() that also is a "single widget". In fact, I'll return a
ListView.builder(). And for this, I need a list, that I already have. So, I just will create a
final variable and create a class constructor to pass this list through a parameter.
Now, in the
buildSuggestion() I'll create an auxiliary list, that will receive different values depending on a condition. In the case of the search field is empty (or
query.isEmpty == true), the auxiliary list will receive a list of recent items searched. In the other case, it'll receive a list of items that contain the text of
query. After, I'll create a
ListView.build that returns the
onTap parameter of
ListTile, I'll define the String
selectedResult equal the text pressed and call the function
showResults(context) that will call the
Now is the time for your developer superpower to take action. I just pass how works the native search mechanic of flutter with a very simple example. You can customize many of these widgets.
Have a suggestion? Leave a comment!