7.4 C
New York
Monday, December 11, 2023

Flutter: Add a Search Field to an App Bar (2 Approaches)

This article walks you through a couple of examples of adding a search field to an app bar in Flutter. The first one uses the AppBar widget (most seen in entertainment apps) and the second one uses the SliverAppBar widget (commonly used in e-commerce apps). Without any further ado, letÂ’s dive right in.

Example 1: Search Field inside AppBar

In general, many entertainment apps (including big ones like Facebook, Youtube, Spotify, etc) donÂ’t show the search field by default but show a search icon button. When this button is pressed, the search field will be somehow displayed. Advertisements

Preview

The demo app we are going to make contains 2 screens (pages): HomePage and SearchPage. The user can move from the HomePage to the SearchPage by tapping the search icon button. The search field will be implemented by using the title argument of the SearchPageÂ’s AppBar.

LetÂ’s see how it works in action:

The Code

The complete source code in ./lib/main.dart with explanations:

// main.dart
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        // Remove the debug banner
        debugShowCheckedModeBanner: false,
        title: 'Kindacode.com',
        theme: ThemeData(
          primarySwatch: Colors.indigo,
        ),
        home: HomePage());
  }
}

// Home Page
class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Kindacode.com'),
        actions: [
          // Navigate to the Search Screen
          IconButton(
              onPressed: () => Navigator.of(context)
                  .push(MaterialPageRoute(builder: (_) => SearchPage())),
              icon: Icon(Icons.search))
        ],
      ),
    );
  }
}

// Search Page
class SearchPage extends StatelessWidget {
  const SearchPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          // The search area here
          title: Container(
        width: double.infinity,
        height: 40,
        decoration: BoxDecoration(
            color: Colors.white, borderRadius: BorderRadius.circular(5)),
        child: Center(
          child: TextField(
            decoration: InputDecoration(
                prefixIcon: Icon(Icons.search),
                suffixIcon: IconButton(
                  icon: Icon(Icons.clear),
                  onPressed: () {
                    /* Clear the search field */
                  },
                ),
                hintText: 'Search...',
                border: InputBorder.none),
          ),
        ),
      )),
    );
  }
}

Example 2: Search Field and SliverAppBar

AdvertisementsSearching is one of the most important features of many e-commerce apps so they usually display the search field in the most recognizable way and also take up a lot of space right from the start (Amazon, Shopee, etc).

Preview

The Code

The full source:

// main.dart
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        // Remove the debug banner
        debugShowCheckedModeBanner: false,
        title: 'Kindacode.com',
        theme: ThemeData(
          primarySwatch: Colors.deepPurple,
        ),
        home: HomePage());
  }
}

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

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: [
          SliverAppBar(
            floating: true,
            pinned: true,
            snap: false,
            centerTitle: false,
            title: Text('Kindacode.com'),
            actions: [
              IconButton(
                icon: Icon(Icons.shopping_cart),
                onPressed: () {},
              ),
            ],
            bottom: AppBar(
              title: Container(
                width: double.infinity,
                height: 40,
                color: Colors.white,
                child: Center(
                  child: TextField(
                    decoration: InputDecoration(
                        hintText: 'Search for something',
                        prefixIcon: Icon(Icons.search),
                        suffixIcon: Icon(Icons.camera_alt)),
                  ),
                ),
              ),
            ),
          ),
          // Other Sliver Widgets
          SliverList(
            delegate: SliverChildListDelegate([
              Container(
                height: 400,
                child: Center(
                  child: Text(
                    'This is an awesome shopping platform',
                  ),
                ),
              ),
              Container(
                height: 1000,
                color: Colors.pink,
              ),
            ]),
          ),
        ],
      ),
    );
  }
}

Recap

WeÂ’ve examined 2 common approaches to implement a search bar in a mobile app. If youÂ’d like to explore more new and interesting stuff about Flutter and Dart, take a look at the following articles:

Advertisements

You can also take a tour around our Flutter topic page or Dart topic page for the latest tutorials and examples.

Advertisements

Related Articles

Latest Articles