(mostly) Automatic search-enabled appBar for flutter

Overview

flutter_search_bar

A simple and mostly automatic material search bar for flutter (dart).

Note: use flutter_search_bar and not search_bar -- I own both packages but I'm just a tad bit locked out of search_bar, so it won't be updated.

Screenshots

Normal state (search is not active yet, only title and actions are set, with the only action being a search button)

Normal State

inBar set to false (background white, back button inherited):

inBar false

inBar set to true (background inherited):

inBar true

Usage

A simple usage example:

class _MyHomePageState extends State<MyHomePage> {
  SearchBar searchBar;
  
  AppBar buildAppBar(BuildContext context) {
    return new AppBar(
      title: new Text('My Home Page'),
      actions: [searchBar.getSearchAction(context)]
    );
  }  
  
  _MyHomePageState() {
    searchBar = new SearchBar(
      inBar: false,
      setState: setState,
      onSubmitted: print,
      buildDefaultAppBar: buildAppBar
    );
  }
  
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: searchBar.build(context)
    );
  }
}

This will create an AppBar with a search button as its only action, and on press the AppBar will turn white and have a TextField inside, allowing user input. Once the user has input something and pressed the "enter" button on their keyboard, it will close and the value will be printed to the debugger.

Using SearchBar

Essentially, this class returns two different app bars based on whether search is active.

The setState callback you pass the search bar can technically be any VoidCallback.

Features and bugs

Please file feature requests and bugs at the issue tracker.

We've recently added support for null-safety in 3.0.0-dev.1 -- if you find any issues, please report them there!

Comments
  • Does not support text input number

    Does not support text input number

    Hi! (first of all great work on flutter search bar)

    ISSUE

    KeyboardType only supports text though what about the cases when we have to deal with numbers? in my case I need to search by number

    image

    and I see in code keyboardType: TextInputType.text,

    should be

    keyboardType: TextInputType.number,

    though this would be have to be an optional settings

    TECHNICAL APPROACH

    @todo

    NOTES

    @todo

    new feature planned 
    opened by edutrul 6
  • No support for dart version > 2.0.0

    No support for dart version > 2.0.0

    environment: sdk: '>=1.20.1 <=2.0.0'

    I'm using Dart version 2.1.0-dev.1.0 and when I want to update the library to the latest version I get this error: The current Dart SDK version is 2.1.0-dev.1.0.flutter-69fce633b7.

    Because "your app" depends on flutter_search_bar >=1.0.3 which requires SDK version >=1.20.1 <=2.0.0, version solving failed. pub get failed (1)

    bug 
    opened by foosionsapps 3
  • Listening for on close

    Listening for on close

    How would I go about adding some kind of listener to perform some actions on close. I thought about using willpopscope but it doesn't do what I was looking for. and I am not sure where to declare the beginSearch method.

    new feature planned 
    opened by Badjessa-git 3
  • Error when trying example on Flutter 0.2.8 and Dart 2.0.0

    Error when trying example on Flutter 0.2.8 and Dart 2.0.0

    The following assertion was thrown building Builder: type '(() => void) => void' is not a subtype of type '(dynamic) => void' Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause.

    bug can't reproduce 
    opened by rodydavis 3
  • Error when I run the example code

    Error when I run the example code

    The context in the example is null Scaffold.of(context) .showSnackBar(new SnackBar(content: new Text('You wrote $value!'))

    when I run the example code. This is with the latest flutter and libs. I copied the example code to a newly generated flutter app.

    More info here: https://docs.flutter.io/flutter/material/Scaffold/of.html

    This is fixing it:

    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(
            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(
            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);
      }
    
      @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!")),
        );
      }
    }
    
    
    opened by ride4sun 3
  • Has the plugin been abandoned?

    Has the plugin been abandoned?

    I can't find the package in the pub.dart.org site any longer and seeing a bunch of Issues a few PRs and no movement I'm wondering if this package has been abandoned.

    opened by warriorCoder 2
  • Localizable string to hintText

    Localizable string to hintText

    I can't set the hintText based on Internationalization because I need to instantiate the _searchBar on the constructor and here I can't access to BuildContext. Any idea?

    new feature 
    opened by rcpassos 2
  • Does not allow user input

    Does not allow user input

    Hi,

    I'm testing your search bar and I see it does not allow user input. Everything is working fine except for the fact that I can't type anything in the textfield. I guess a fix is to update InputValue in setState() ?

    bug can't reproduce 
    opened by bjornbjorn 2
  • Include an example screenshot in the documentation

    Include an example screenshot in the documentation

    Hi, this looks promising. It would be great if you can include a screenshot in your Readme/documentation so people don't have to set it all up until they see what it looks like :)

    opened by Areiser 2
  • TextInputType.number option added

    TextInputType.number option added

    I added TextInputType.number option for search bar. It is related to https://github.com/ArcticZeroo/flutter-search-bar/issues/32 issue. But, I wasn't able to run and test it. Because I got the following error when I tried to run.

    Launching lib\main.dart on AOSP on IA Emulator in debug mode...
    Running Gradle task 'assembleDebug'...
    √ Built build\app\outputs\flutter-apk\app-debug.apk.
    Installing build\app\outputs\flutter-apk\app.apk...
    E/AndroidRuntime(24565): FATAL EXCEPTION: main
    E/AndroidRuntime(24565): Process: com.example.example, PID: 24565
    E/AndroidRuntime(24565): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.example/com.example.example.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.example.example.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.example-hx1kBentbJK6hGxXINBPzw==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.example-hx1kBentbJK6hGxXINBPzw==/lib/x86, /data/app/com.example.example-hx1kBentbJK6hGxXINBPzw==/base.apk!/lib/x86, /system/lib]]
    E/AndroidRuntime(24565): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2843)
    E/AndroidRuntime(24565): 	at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
    E/AndroidRuntime(24565): 	at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
    E/AndroidRuntime(24565): 	at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
    E/AndroidRuntime(24565): 	at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
    E/AndroidRuntime(24565): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
    E/AndroidRuntime(24565): 	at android.os.Handler.dispatchMessage(Handler.java:106)
    E/AndroidRuntime(24565): 	at android.os.Looper.loop(Looper.java:193)
    E/AndroidRuntime(24565): 	at android.app.ActivityThread.main(ActivityThread.java:6669)
    E/AndroidRuntime(24565): 	at java.lang.reflect.Method.invoke(Native Method)
    E/AndroidRuntime(24565): 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    E/AndroidRuntime(24565): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
    E/AndroidRuntime(24565): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.example.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.example-hx1kBentbJK6hGxXINBPzw==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.example-hx1kBentbJK6hGxXINBPzw==/lib/x86, /data/app/com.example.example-hx1kBentbJK6hGxXINBPzw==/base.apk!/lib/x86, /system/lib]]
    E/AndroidRuntime(24565): 	at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
    E/AndroidRuntime(24565): 	at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
    E/AndroidRuntime(24565): 	at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    E/AndroidRuntime(24565): 	at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
    E/AndroidRuntime(24565): 	at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:41)
    E/AndroidRuntime(24565): 	at android.app.Instrumentation.newActivity(Instrumentation.java:1215)
    E/AndroidRuntime(24565): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2831)
    E/AndroidRuntime(24565): 	... 11 more
    
    opened by gozeloglu 1
  • Added missing repository url

    Added missing repository url

    In this package's pub page, the homepage is set to https://frozor.io, and that's perfectly ok.

    Though, there is no direct link to this GitHub repo, which means that the visibility of the code is very bad.

    This PR is a simple fix for this problem.

    opened by cmaster11 1
  • onClosed() is not fired when go

    onClosed() is not fired when go "back" on navigation bar or by gesture

    Hi! Would you guys be able to look at this. Inside scaffold's body I have a FutureBuilder and I'm filtering data in onChanged() function.

      _ProductsScreenState() {
        searchBar = SearchBar(
            setState: setState,
            buildDefaultAppBar: buildAppBar,
            inBar: true,
            hintText: "Wyszukaj...",
            onSubmitted: print,
            onChanged: (value) async {
              if (!["", null, false, 0].contains(value)) {
                var products = await productsService.getProducts();
                var filteredProducts =
                    products.where((element) => element.ean!.contains(value) || element.name.contains(value) || element.code.contains(value)).toList();
                setState(() {
                  _products = Future.value(filteredProducts);
                });
              } else {
                _products = productsService.getProducts();
              }
            },
            onCleared: () {
              _products = productsService.getProducts();
            },
            onClosed: () {
              print("onClosed");
              _products = productsService.getProducts();
            });
      }
    

    Function onClosed() is fired only when I tap on "back" icon provided by this plugin.

    bug can't reproduce 
    opened by troncomputers 2
  • Unable to show search bar

    Unable to show search bar

    When I try to tap on the search button, the search bar doesn't open and just throws an error:

    The method 'addLocalHistoryEntry' was called on null. Receiver: null Tried calling: addLocalHistoryEntry(Instance of 'LocalHistoryEntry')

    What's the matter with it?

    bug can't reproduce 
    opened by Switernal 4
  • Unable to close the the search bar

    Unable to close the the search bar

    I'm unable to close the searchbar with the back arrow that appears on it. I've tried numerous things. Poping with navigator, etc..

    I need to use inBar:true

    image

    opened by juvanjan 1
  • Fix bad input field text color

    Fix bad input field text color

    Premise

    Sorry for the mess of this PR, but the Android example was lacking the main activity file, so I recreated it with flutter create ., which in turn let to clearly more stuff being generated.

    The re;evant altered code is in lib/src/flutter_search_bar_base.dart.

    All of this has also been compiled/edited with Flutter 1.22.2

    Bug

    While trying to use the bar with a heavily dark customized theme (e.g. dark primary color and quite an amount of other edits), the input field was showing dark text, the cursor color was dark, and hint text was black.

    Then, when I tried to use the bare Android example, that was having the same issue too.

    I think that, inbetween Flutter version changes, the input field is not behaving like you originally planned it to.

    The fix here is to use some default values, which work correctly on a standard dark theme, but also work correctly if a custom one is passed.

    opened by cmaster11 4
Owner
Spencer
Spencer
🚰 A BehaviorSubject for Flutter with automatic persist and hydrate

Hydrated Hydrated provides a Subject that automatically persists to Flutter's local storage and hydrates on creation! Easy to consume All values are p

Solid Software 114 Oct 2, 2022
Some UI mostly use when develop Flutter app

Demo Flutter - Some common UI in Flutter App include Hero Animation Screen - How to play with hero widget. Simple Animation Screen - Some simple anima

Duy Tran 57 Jul 24, 2022
A Flutter Widget for an AppBar that is initially flush with the body and elevated when scrolled

appbar_elevation A Flutter Widget for an AppBar that is initially flush with the body and elevated when scrolled. Usage Use the ScrollActivatedAppBarE

Amit Kotlovski 8 Sep 22, 2021
Automatic source code generation for Dart

Overview source_gen provides utilities for automated source code generation for Dart: A framework for writing Builders that consume and produce Dart c

Dart 418 Dec 30, 2022
This is a expenses app which keeps a track of the money spend. Mostly helpful for college students like me...

expenses_app A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if

null 2 Jun 5, 2022
This is a mostly auto-generated library for using the mattermost api from Dart.

Mattermost API Client in Dart This is an implementation of a Mattermost API client in dart. It is not the only one, but it has significant advantages

null 1 Jun 15, 2022
Github-search - Allows users to search users on github Uses flutter

Github Search Github Search is a cross-platform mobile application powered by Flutter Framework and Github API. The application was built with simplic

Saul 3 Sep 13, 2022
A google browser clone which is made by using flutter and fetching the google search api for the search requests.

google_clone A new Flutter project. Project Preview Getting Started This project is a starting point for a Flutter application. A few resources to get

Priyam Soni 2 May 31, 2022
Starlight search bar - Starlight search bar with flutter

starlight_search_bar If you find the easiest way to search your item, this is fo

Ye Myo Aung 1 Apr 20, 2022
181011450390-FLUTTER-CHALLENGE - Example GitHub Search app built in Flutter & RxDart

Example GitHub Search app built in Flutter & RxDart Simple app using the Flutter

null 1 Jan 3, 2022
Ali Türkay AVCI 1 Jan 20, 2022
A platform-adaptive search for Flutter

Flutter Platform Search Flutter platform search is an abstract implementation of the Flutter search delegate. It is a time saving way to implement a p

QuickBird Studios 32 Dec 31, 2022
A flutter search engine based on MediaWiki with caching.

Table of contents Project Description Working App Architecture BLoC/Cubit Pattern Caching using HiveDB App UI Project Setup To-Do How to get started w

Shashwat Joshi 42 Nov 7, 2022
A mobile application that allows you to search and fetch recipes using Flutter, TheMealDB and Domain Driven Design

recipe_app A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if th

Johnny Nguyen 0 Dec 4, 2021
Search and view popular Youtube videos with Youtube API in Flutter App

getx_bottom_nav_sample The sample of AnimatedBottomNavBar with GetX 주요 Package 설명 1.url_launcher url_launcher pub.dev flutter 에서 인앱, 외부 브라우저로 연길 시켜 주는

Jacob Ko 1 Dec 25, 2021
Flutter Search bar

search_bar Flutter search bar Search suggestion and search lists Demo video Record_2021-12-09-19-59-51.mp4 ScreenShots Getting Started This project is

Aravind B 0 Dec 9, 2021
A music player app that allows you to search for music by artist made using Flutter

Music Player A music player app that allows you to search for music by artist. Music source from iTunes affiliate API. Made using Flutter with simple

muhibush 5 Feb 5, 2022
A fully functional Movies Application built with Flutter. The application built with null safety and clean architecture, also uses OMDB API for fetching movies in the search item

Cinema DB Project Details This project uses null safety feature Project uses clean code architecture (Uncle Bob's Architecture) Project can run on bot

Dhruvam 2 Oct 1, 2022