How To Create Search Bar Using Flutter Android App

admin_img Posted By Bajarangi soft , Posted On 27-11-2020

Apps love their search bars. Every popular platform has a dedicated class to provide a search bar — all except Flutter it would seem. A search bar offers a means for the user to quickly search for content applicable to the app being used. Many articles have been written on the subject offering code that implements a search bar of one variation or another.

How To Create Search Bar Using Flutter Android App

Search Bar 
Step 1 
We cannot directly remove the time stamp from  Search Bar   but using the intl.dart package we can easily filter the date stamp from time stamp. So open your flutter project’s pubspec.yaml in code .

dependencies:
  flutter:
    sdk: flutter
  flutter_search_bar: ^2.1.0

Step 2
After done saving the pubspec.yaml file, Open your flutter project root folder in Command Prompt or Terminal and execute flutter pub get command.

flutter pub get



Complete Code For Search Bar In Flutter
main.dart
import 'package:flutter/material.dart';
import 'package:flutter_search_bar/flutter_search_bar.dart';

void main() {
  runApp(new SearchBarDemoApp());
}

class SearchBarDemoApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
        title: 'Search Bar Demo',
        theme: new ThemeData(primarySwatch: Colors.blue),
        home: new SearchBarDemoHome());
  }
}

class SearchBarDemoHome extends StatefulWidget {
  @override
  _SearchBarDemoHomeState createState() => new _SearchBarDemoHomeState();
}

class _SearchBarDemoHomeState extends State<SearchBarDemoHome> {
  SearchBar searchBar;
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  AppBar buildAppBar(BuildContext context) {
    return new AppBar(
      backgroundColor: Colors.orange,
        title: new Text('Search Bar Demo'),
        actions: [searchBar.getSearchAction(context)]);
  }

  void onSubmitted(String value) {
    setState(() => _scaffoldKey.currentState
        .showSnackBar(new SnackBar(content: new Text('You wrote $value!'))));
  }

  _SearchBarDemoHomeState() {
    searchBar = new SearchBar(
        inBar: false,
        buildDefaultAppBar: buildAppBar,
        setState: setState,
        onSubmitted: onSubmitted,
        onCleared: () {
          print("cleared");
        },
        onClosed: () {
          print("closed");
        });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: searchBar.build(context),
      key: _scaffoldKey,
      body: new Center(
          child: new Text("Don't look at me! Press the search button!")),
    );
  }
}

Related Post