DEV Community

Finite Field
Finite Field

Posted on

Level Up Your Flutter App: Mastering the SearchBar Widget

In today's apps, users expect seamless search functionality. Whether it's finding a specific product, locating a contact, or sifting through a list of articles, a good search experience is crucial. Luckily, Flutter provides the SearchBar widget to make implementing search functionality a breeze.

This post will guide you through everything you need to know to effectively use the SearchBar in your Flutter applications. We'll cover basic setup, handling user input, displaying results, and some common customization options.

Let's dive in!

Getting Started: The Basic Setup

Before we get to the search logic, we need to set up our SearchBar widget within our Flutter UI. Here's the most basic implementation:

import 'package:flutter/material.dart';

class SearchExample extends StatefulWidget {
  @override
  _SearchExampleState createState() => _SearchExampleState();
}

class _SearchExampleState extends State<SearchExample> {
  String _searchText = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Search Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: SearchBar(
          hintText: 'Search here...',
          onChanged: (text) {
            setState(() {
              _searchText = text;
            });
            // You'll add search logic here later
          },
        ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

What's happening here?

  • SearchBar Widget: We've added the SearchBar widget directly into our widget tree, which takes care of the visual layout of the search bar.
  • hintText: This provides a helpful placeholder text inside the search bar.
  • onChanged Callback: This function is triggered every time the user types or deletes something in the search bar. This is where our search logic will live!
  • _searchText Variable: We use a StatefulWidget to manage the search text as the user types.
  • setState: We update the _searchText using setState, which triggers a rebuild and shows the updated value.

If you run this code, you'll have a basic working search bar that updates the _searchText variable!

Adding Search Logic

Now, let's make the search bar actually do something. We'll assume we have a simple list of items that we want to search through. Here's how we can update the code:

import 'package:flutter/material.dart';

class SearchExample extends StatefulWidget {
  @override
  _SearchExampleState createState() => _SearchExampleState();
}

class _SearchExampleState extends State<SearchExample> {
  String _searchText = '';
  List<String> _allNames = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry', 'Fig']; //Example Data
  List<String> _filteredNames = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Search Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            SearchBar(
              hintText: 'Search Names...',
              onChanged: (text) {
                setState(() {
                    _searchText = text;
                  if (text.isNotEmpty) {
                   _filteredNames = _allNames.where((name) =>
                          name.toLowerCase().contains(text.toLowerCase()))
                            .toList();
                  } else {
                    _filteredNames = [];
                  }

                });
              },
            ),
            SizedBox(height: 16),
            Expanded(
              child: ListView.builder(
                  itemCount: _searchText.isEmpty? _allNames.length : _filteredNames.length,
                  itemBuilder: (context, index) {
                  return ListTile(
                    title: Text(_searchText.isEmpty? _allNames[index] : _filteredNames[index]),
                  );
                  }
              ),
            ),
          ],
        ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Changes:

  • _allNames: A sample list of strings we'll be searching through.
  • _filteredNames: This list will store the search results.
  • Search Logic: Inside the onChanged callback:
    • We check if the search text is not empty. If it is not empty we use the .where method to filter the _allNames based on a substring match (case-insensitive).
    • If the search text is empty we set the _filteredNames to empty list.
  • ListView.builder Now we display either all names or the filtered name depending on the state of the search text.

Now, as you type in the search bar, the list of names will update in real-time to show only the matching results.

Customizing the SearchBar

The SearchBar widget offers several ways to customize its appearance and behavior. Here are a few of the most common:

  • controller: You can use a TextEditingController to control the input of the search bar. This is useful if you need to pre-populate the search bar or programmatically clear it.
  • leading and trailing: Add widgets (such as Icons) before and after the input field.
  • backgroundColor and other styling properties: Use these to change the look and feel of the search bar.

Here's a quick example of using a leading icon and changing the background color:

SearchBar(
  hintText: 'Search...',
  backgroundColor: MaterialStateProperty.all(Colors.grey[200]),
  leading: Icon(Icons.search),
  onChanged: (text) {
    // ...
  },
);
Enter fullscreen mode Exit fullscreen mode

Beyond the Basics

This blog post provides a foundation for working with the SearchBar widget. Here are some ideas for taking your search functionality further:

  • Debouncing: Prevent your search logic from running on every single keystroke by using a debouncer. This can significantly improve performance.
  • API Integration: Fetch search results from an API instead of a local list.
  • Loading Indicators: Provide feedback to the user while results are loading from an API.
  • Search Suggestions: Offer suggestions as the user types to help them find what they are looking for quickly.

Conclusion

The SearchBar widget is a powerful and flexible tool for building search functionality in Flutter. By following the techniques outlined in this blog post, you'll be well on your way to crafting excellent user experiences in your Flutter applications.

At Finite Field, we understand the power of cutting-edge features like SearchBar. As a dedicated app development company, we leverage these kinds of tools, along with deep expertise in Flutter and Dart, to craft innovative and high-quality mobile applications for our clients. If you're looking for a partner to bring your app idea to life with a focus on maintainable and scalable code, we'd love to hear from you.

Top comments (0)