How To Create Search Bar Flutter

Master search implementation in Flutter for cross-platform mobile apps. Learn CustomSearchDelegate, SearchBar widget, and best practices for intuitive search experiences.

Why Search Bars Matter in Mobile Apps

Search functionality is essential for mobile applications with substantial content or data. Whether you are building an e-commerce app, a content management system, or a product catalog, an effective search bar helps users find what they need quickly and efficiently.

Search bars serve as the primary navigation mechanism for users looking for specific content within an application. In cross-platform mobile development, implementing a consistent and intuitive search experience across iOS and Android is crucial for user satisfaction. The search bar widget will search for components in real-time depending on an input substring, providing immediate feedback as users type their queries.

Flutter provides multiple approaches to implement search, from the traditional SearchDelegate pattern to the modern SearchBar widget. Understanding both approaches allows you to choose the one that best fits your application's requirements and design goals. By leveraging Flutter's widget-based architecture, you can create search interfaces that look native on both platforms while sharing a single codebase through our mobile development services. Advanced implementations can even integrate AI-powered search capabilities to provide intelligent recommendations and natural language understanding.

Flutter Search Implementation Options

Choose the approach that fits your needs

CustomSearchDelegate

Full-featured search page with built-in navigation, suggestions, and results display using Flutter's showSearch() method.

SearchBar Widget

Modern inline search component with extensive customization options for styling and behavior.

Real-Time Filtering

Filter search results instantly as users type, providing immediate feedback and improved user experience.

Autocomplete

Display suggestion dropdowns that help users complete their searches faster and reduce typos.

Creating a Search Bar Using CustomSearchDelegate

The traditional approach to implementing search in Flutter involves creating a class that extends SearchDelegate and overriding four essential methods. This pattern provides a complete search experience including a dedicated search page with suggestions and results.

Before implementing search functionality, ensure your Flutter project is properly configured with a MaterialApp at the root. The Material Design components provide the foundation for search-related widgets and animations. When creating the search functionality, focus on constructing the search delegate rather than the app structure itself.

Setting Up the Search Trigger

The search interface is typically accessed through an IconButton placed in the app bar. This button uses the magnifying glass icon to signal its purpose to users, following established design conventions that users recognize across applications and platforms. Because we are making a button that displays the search bar when clicked, we use the IconButton widget which generates a small animation when pressed, indicating that the user's selection was registered by the app.

IconButton Search Trigger
1class SearchScreen extends StatefulWidget {2 const SearchScreen({Key? key}) : super(key: key);3 4 @override5 State<SearchScreen> createState() => _SearchScreenState();6}7 8class _SearchScreenState extends State<SearchScreen> {9 @override10 Widget build(BuildContext context) {11 return Scaffold(12 appBar: AppBar(13 title: const Text('Product Search'),14 actions: [15 IconButton(16 icon: const Icon(Icons.search_outlined),17 onPressed: () {18 showSearch(19 context: context,20 delegate: CustomSearchDelegate()21 );22 },23 )24 ],25 ),26 );27 }28}

CustomSearchDelegate Implementation

The CustomSearchDelegate class extends SearchDelegate and provides implementations for four required methods. These methods control different aspects of the search interface:

  • buildActions: Widgets displayed in the search bar's trailing area, typically a clear button that empties the current query and improves user convenience since users can clear text all at once rather than character by character

  • buildLeading: Widget shown at the start of the search bar, usually a back button that closes the search interface and returns users to their previous context

  • buildResults: Displayed when the user submits their query, showing the final filtered results after comparing the search text against your data list using ListView.builder for efficient rendering

  • buildSuggestions: Shows real-time suggestions as the user types, with the search suggestions box becoming more accurate and nearer to the term the user is attempting to search for as they continue typing

CustomSearchDelegate Class
1class CustomSearchDelegate extends SearchDelegate {2 List<String> searchTerms = [3 "Apple", "Banana", "Mango", "Pear",4 "Watermelons", "Blueberries", "Pineapples", "Strawberries"5 ];6 7 @override8 List<Widget>? buildActions(BuildContext context) {9 return [10 IconButton(11 onPressed: () {12 query = '';13 },14 icon: Icon(Icons.clear),15 ),16 ];17 }18 19 @override20 Widget? buildLeading(BuildContext context) {21 return IconButton(22 onPressed: () {23 close(context, null);24 },25 icon: Icon(Icons.arrow_back),26 );27 }28 29 @override30 Widget buildResults(BuildContext context) {31 List<String> matchQuery = [];32 for (var item in searchTerms) {33 if (item.toLowerCase().contains(query.toLowerCase())) {34 matchQuery.add(item);35 }36 }37 return ListView.builder(38 itemCount: matchQuery.length,39 itemBuilder: (context, index) {40 return ListTile(41 title: Text(matchQuery[index]),42 );43 },44 );45 }46 47 @override48 Widget buildSuggestions(BuildContext context) {49 List<String> matchQuery = [];50 for (var item in searchTerms) {51 if (item.toLowerCase().contains(query.toLowerCase())) {52 matchQuery.add(item);53 }54 }55 return ListView.builder(56 itemCount: matchQuery.length,57 itemBuilder: (context, index) {58 return ListTile(59 title: Text(matchQuery[index]),60 );61 },62 );63 }64}

Using the Modern SearchBar Widget

Flutter's Material Design library includes a dedicated SearchBar widget that offers more flexibility for custom search interfaces. This widget is designed to be used within a SearchAnchor, which provides the search view infrastructure.

SearchBar Properties and Configuration

The SearchBar widget provides extensive customization options through its constructor parameters. Key properties include controller for managing the text input, focusNode for controlling focus behavior, and hintText for displaying placeholder guidance that helps users understand what to search for.

For TextDirection.ltr, the leading widget appears on the left side of the bar and should contain either a navigational action (such as a menu or up-arrow) or a non-functional search icon. The trailing is an optional list appearing at the other end of the search bar. Typically only one or two action icons are included, such as additional modes of searching (like voice search), a separate high-level action (such as current location), or an overflow menu. The background fill color is controlled through the backgroundColor property, which accepts a WidgetStateProperty for different visual states, while the elevation property determines the shadow depth of the search bar.

SearchBar Widget Example
1SearchBar(2 controller: searchController,3 focusNode: searchFocusNode,4 hintText: 'Search for products...',5 leading: Icon(Icons.search),6 trailing: [7 IconButton(8 icon: Icon(Icons.filter_list),9 onPressed: () { /* Show filters */ },10 ),11 ],12 onChanged: (value) {13 // Handle text changes for real-time filtering14 },15 onSubmitted: (value) {16 // Handle search submission17 },18 elevation: WidgetStateProperty.all(4.0),19 backgroundColor: WidgetStateProperty.all(Colors.white),20 padding: WidgetStateProperty.all(EdgeInsets.symmetric(horizontal: 16)),21)

Best Practices for Search Bar Implementation

Creating an effective search experience requires attention to both functionality and user experience design. Following these best practices ensures your search implementation delivers professional results that integrate seamlessly with your web development strategy.

Design Guidelines

  • Positioning: Place search bar in top-right or top-center of the screen. Either location guarantees the search feature is visible and accessible to those who need it. If search is your key navigational tool, make it prominent and displayed prominently on page load.

  • Size: Scale the search bar by other header elements--large enough to be visible on a visual scan, but not so huge that it steals attention from other important actions.

  • Icons: The magnifying glass icon is a well-recognized search symbol. Icons take up less space and are easier to recognize than words, making them ideal for compact mobile interfaces.

  • Placeholder text: Display guidance such as "Try hats, jeans, bags..." or simply "Search..." to help users understand what they can search for.

Autocomplete and Suggestions

Autocomplete displays options in a menu below the search as users type. Predictions can be adjusted to your app's specific content, giving consumers confidence they are getting what they are looking for. Don't overwhelm users with too many suggestions--one to ten is typically a good range, depending on your app's content size. Research indicates that autocomplete features, common across eCommerce platforms, help users accurately spell words or find what they need without visiting a separate search page.

Performance Optimization

To improve search performance, consider adding search ahead and autocomplete features, using product filters for eCommerce applications, and enabling advanced search options. Product filters enable consumers to limit what appears in search results, including size, brand, material, or color restrictions. Unless you anticipate a technologically sophisticated user base, hide advanced search features such as categories, filters, and precise matching by default to keep the UI tidy and easy to use.

Mobile Considerations

The proliferation of smartphones has influenced UI best practices across the board. Make sure your search box and button are visible and clickable on touch screens. Display your search bar prominently on both mobile and desktop. Put the search bar in the upper right corner where most people expect to see it. If you sell high-priced products with lengthy purchasing processes, allow users to bookmark search results so they can return and continue their journey.

Complete Implementation Example

Here is a comprehensive example demonstrating a fully-featured product search implementation. This complete runnable example combines the CustomSearchDelegate pattern with real-time filtering, proper state management, and intuitive user feedback through icons and animations. The code demonstrates proper navigation controls, clear visual hierarchy, and a polished user experience that works consistently across iOS and Android platforms.

Complete Product Search Implementation
1import 'package:flutter/material.dart';2 3void main() {4 runApp(const MyApp());5}6 7class MyApp extends StatelessWidget {8 const MyApp({Key? key}) : super(key: key);9 10 @override11 Widget build(BuildContext context) {12 return MaterialApp(13 title: 'Flutter Search Demo',14 theme: ThemeData(primarySwatch: Colors.blue),15 home: const SearchScreen(),16 );17 }18}19 20class SearchScreen extends StatefulWidget {21 const SearchScreen({Key? key}) : super(key: key);22 23 @override24 State<SearchScreen> createState() => _SearchScreenState();25}26 27class _SearchScreenState extends State<SearchScreen> {28 @override29 Widget build(BuildContext context) {30 return Scaffold(31 appBar: AppBar(32 title: const Text('Product Search'),33 actions: [34 IconButton(35 icon: const Icon(Icons.search),36 onPressed: () {37 showSearch(context: context, delegate: ProductSearchDelegate());38 },39 ),40 ],41 ),42 body: const Center(43 child: Text('Tap the search icon to find products'),44 ),45 );46 }47}48 49class ProductSearchDelegate extends SearchDelegate {50 final List<String> products = [51 'iPhone 15 Pro', 'Samsung Galaxy S24', 'Google Pixel 8',52 'MacBook Pro', 'Dell XPS', 'HP Spectre',53 'AirPods Pro', 'Sony WH-1000XM5', 'Bose QuietComfort',54 ];55 56 @override57 List<Widget>? buildActions(BuildContext context) => [58 if (query.isNotEmpty)59 IconButton(60 onPressed: () { query = ''; },61 icon: const Icon(Icons.clear),62 ),63 ];64 65 @override66 Widget? buildLeading(BuildContext context) => IconButton(67 onPressed: () { close(context, null); },68 icon: const Icon(Icons.arrow_back),69 );70 71 @override72 Widget buildResults(BuildContext context) {73 final results = products74 .where((p) => p.toLowerCase().contains(query.toLowerCase()))75 .toList();76 77 return ListView.builder(78 itemCount: results.length,79 itemBuilder: (context, index) => ListTile(80 leading: const Icon(Icons.shopping_bag),81 title: Text(results[index]),82 onTap: () { close(context, results[index]); },83 ),84 );85 }86 87 @override88 Widget buildSuggestions(BuildContext context) {89 final suggestions = query.isEmpty90 ? products91 : products92 .where((p) => p.toLowerCase().contains(query.toLowerCase()))93 .toList();94 95 return ListView.builder(96 itemCount: suggestions.length,97 itemBuilder: (context, index) => ListTile(98 leading: const Icon(Icons.history),99 title: Text(suggestions[index]),100 onTap: () { query = suggestions[index]; },101 ),102 );103 }104}

Conclusion

Implementing a search bar in Flutter involves choosing between two primary approaches. The traditional SearchDelegate pattern is best for full-featured search pages with built-in navigation, suggestions, and results display through Flutter's showSearch() method. The modern SearchBar widget is best for inline search interfaces with maximum customization flexibility for styling and behavior.

Both approaches support real-time filtering, autocomplete suggestions, and intuitive navigation. The search bar is a fundamental UI feature that allows users to input search queries and submit them for processing. Some search bars contain additional functionality like autocomplete recommendations, filters, or recent searches.

The key to success lies in following established UX patterns--strategic placement in top-right or top-center, clear visual hierarchy with recognizable icons, and thoughtful feedback mechanisms through real-time filtering. By implementing the best practices outlined in this guide, you can deliver a professional search experience that works consistently across iOS and Android platforms.

For organizations looking to build robust cross-platform mobile applications with intuitive search experiences, our mobile development team specializes in creating applications that prioritize user experience and seamless functionality. Combined with AI automation services, organizations can implement intelligent search features that learn from user behavior and provide increasingly personalized results.

Frequently Asked Questions

Ready to Build Your Mobile App?

Our Flutter development team specializes in creating cross-platform mobile applications with intuitive search experiences and seamless user interfaces.

Sources

  1. GeeksforGeeks - Flutter Search Bar - Comprehensive tutorial covering the CustomSearchDelegate approach with detailed code examples.

  2. Scaler Topics - How to Create a Search Bar in Flutter - In-depth guide covering custom search bar implementation and best practices.

  3. Flutter API Documentation - SearchBar Class - Official reference for the modern SearchBar widget properties.