dropdown_search 0.4.3

  • Readme
  • Changelog
  • Example
  • Installing
  • 90

Flutter DropdownSearch

Flutter simple and robust DropdownSearch with item search feature, making it possible to use an offline item list or filtering URL for easy customization.

Build

Key FeaturesExamplesLicense

Dropdown search

Key Features #

  • Online and offline items
  • Searchable dropdown
  • Three dropdown mode: Menu/ BottomSheet/ Dialog
  • Material dropdown
  • Easy customizable UI
  • Handle Light and Dark theme
  • Easy implementation into statelessWidget

packages.yaml #

dropdown_search: <lastest version>

Import #

import 'package:dropdown_search/dropdown_search.dart';

Simple implementation #

DropdownSearch<String>(
    mode: Mode.MENU,
    showSelectedItem: true,
    items: ["Brazil", "Italia (Disabled)", "Tunisia", 'Canada'],
    label: "Menu mode",
    hint: "country in menu mode",
    popupItemDisabled: (String s) => s.startsWith('I'),
    onChanged: print,
    selectedItem: "Brazil"),

customize showed field (itemAsString) #

DropdownSearch<UserModel>(
  label: "Name",
  onFind: (String filter) => getData(filter),
  itemAsString: (UserModel u) => u.userAsStringByName(),
  onChanged: (UserModel data) => print(data),
),

DropdownSearch<UserModel>(
  label: "Name",
  onFind: (String filter) => getData(filter),
  itemAsString: (UserModel u) => u.userAsStringById(),
  onChanged: (UserModel data) => print(data),
),

customize Filter Function #

DropdownSearch<UserModel>(
  label: "Name",
  filterFn: (user, filter) => user.userFilterByCreationDate(filter),
  onFind: (String filter) => getData(filter),
  itemAsString: (UserModel u) => u.userAsStringByName(),
  onChanged: (UserModel data) => print(data),
),

customize Search Mode #

DropdownSearch<UserModel>(
  mode: Mode.BOTTOM_SHEET,
  label: "Name",
  onFind: (String filter) => getData(filter),
  itemAsString: (UserModel u) => u.userAsString(),
  onChanged: (UserModel data) => print(data),
),

Validation #

DropdownSearch(
  items: ["Brazil", "France", "Tunisia", "Canada"],
  label: "Country",
  onChanged: print,
  selectedItem: "Tunisia",
  validator: (String item) {
    if (item == null)
      return "Required field";
    else if (item == "Brazil")
      return "Invalid item";
    else
      return null;
  },
);

Endpoint implementation (using Dio package) #

DropdownSearch<UserModel>(
  label: "Name",
  onFind: (String filter) async {
    var response = await Dio().get(
        "http://5d85ccfb1e61af001471bf60.mockapi.io/user",
        queryParameters: {"filter": filter},
    );
    var models = UserModel.fromJsonList(response.data);
    return models;
  },
  onChanged: (UserModel data) {
    print(data);
  },
);

Layout customization #

You can customize the layout of the DropdownSearch and its items. EXAMPLE

PropertiesDescription
labelDropDownSearch label
showSearchBoxshow/hide the search box
isFilteredOnlinetrue if the filter on items is applied onlie (via API)
showClearButtonshow/hide clear selected item
itemsoffline items list
selectedItemselected item
onFindfunction that returns item from API
onChangedcalled when a new item is selected
dropdownBuilderto customize list of items UI
popupItemBuilderto customize selected item
validatorfunction to apply the validation formula
searchBoxDecorationdecoration for the search box
popupBackgroundColorbackground color for the dialog/menu/bottomSheet
popupTitleCustom widget for the popup title
itemAsStringcustomize the fields the be shown
filterFncustom filter function
enabledenable/disable dropdownSearch
modeMENU / DIALOG/ BOTTOM_SHEET
maxHeightthe max height for dialog/bottomSheet/Menu
dialogMaxWidththe max width for the dialog
showSelectedItemmanage selected item visibility (if true, the selected item will be highlighted)
compareFnFunction(T item, T selectedItem), custom comparing function
dropdownSearchDecorationDropdownSearch input decoration
emptyBuildercustom layout for empty results
loadingBuildercustom layout for loading items
errorBuildercustom layout for error
autoFocusSearchBoxthe search box will be focused if true
popupShapecustom shape for the popup
autoValidatehandle auto validation
onSavedAn optional method to call with the final value when the form is saved via
validatorAn optional method that validates an input. Returns an error string to display if the input is invalid, or null otherwise.
clearButtoncustomize clear button widget
dropDownButtoncustomize dropdown button widget
dropdownBuilderSupportsNullItemIf true, the dropdownBuilder will continue the uses of material behavior. This will be useful if you want to handle a custom UI only if the item !=null
popupItemDisableddefines if an item of the popup is enabled or not, if the item is disabled, it cannot be clicked
popupBarrierColorset a custom color for the popup barrier

Attention #

To use a template as an item type, and you don't want to use a custom fonction itemAsString and compareFn you need to implement toString, equals and hashcode, as shown below:

class UserModel {
  final String id;
  final DateTime createdAt;
  final String name;
  final String avatar;

  UserModel({this.id, this.createdAt, this.name, this.avatar});

  factory UserModel.fromJson(Map<String, dynamic> json) {
    if (json == null) return null;
    return UserModel(
      id: json["id"],
      createdAt:
          json["createdAt"] == null ? null : DateTime.parse(json["createdAt"]),
      name: json["name"],
      avatar: json["avatar"],
    );
  }

  static List<UserModel> fromJsonList(List list) {
    if (list == null) return null;
    return list.map((item) => UserModel.fromJson(item)).toList();
  }

  ///this method will prevent the override of toString
  String userAsString() {
    return '#${this.id} ${this.name}';
  }

  ///this method will prevent the override of toString
  bool userFilterByCreationDate(String filter) {
    return this?.createdAt?.toString()?.contains(filter);
  }

  ///custom comparing function to check if two users are equal
  bool isEqual(UserModel model) {
    return this?.id == model?.id;
  }

  @override
  String toString() => name;
}

View more Examples #

Support #

If this plugin was useful to you, helped you to deliver your app, saved you a lot of time, or you just want to support the project, I would be very grateful if you buy me a cup of coffee.

Buy Me A Coffee

License #

MIT

[0.4.3] - 2020.06.04 #

  • remove dropDownSearchDecoration duplication
  • add popupBarrierColor feature

[0.4.2] - 2020.05.23 #

  • add popupItemDisabled feature, to manage popupItems accessibility

[0.4.1] - 2020.05.17 #

  • handle dark and light theme
  • handle dropdownBuilder if item is Null

[0.4.0] - 2020.05.15 #

  • add dropdown icon customization
  • add clear button icon customization

[0.3.9] - 2020.05.12 #

  • manage default border color

[0.3.8] - 2020.05.11 #

  • fix issue: default selected item

[0.3.7] - 2020.05.10 #

  • update description

[0.3.6] - 2020.05.10 #

  • update description

[0.3.5] - 2020.05.10 #

  • fix issue

[0.3.4] - 2020.05.10 #

  • Integrate material design
  • make DropdownSearch as item of a form
  • manage validation form

[0.3.4] - 2020.05.01 #

  • fix bug error widget

[0.3.2] - 2020.05.01 #

  • add autoFocus searchBox feature

[0.3.1] - 2020.04.29 #

  • fix bug: filter items
  • fix menu mode background color

[0.3.0] - 2020.04.29 #

  • fix bug: empty items online

[0.2.9] - 2020.04.29 #

Added callbacks #

  • emptyBuilder
  • loadingBuilder
  • errorBuilder

Improvement #

  • improve Menu mode
  • improve bottomSheet mode

[0.2.8] - 2020.04.24 #

  • minor improvement

[0.2.7] - 2020.04.24 #

  • minor improvement

[0.2.6] - 2020.04.23 #

  • Health suggestions

[0.2.5] - 2020.04.23 #

  • Add showSelected option

[0.2.4] - 2020.04.14 #

  • Improve performance

[0.2.3] - 2020.04.13 #

  • Improve performance

[0.2.2] - 2020.04.13 #

  • BugFix

[0.2.1] - 2020.04.01 #

  • BugFix

[0.2.0] - 2020.04.01 #

  • Update README.md

[0.1.9] - 2020.04.01 #

  • Update README.md

[0.1.8] - 2020.04.01 #

  • Add catch error
  • Add Feature : Filter Function as parameter
  • Add Feature : enable/disable
  • Add Feature : add three mode : Menu, BottomSheet and Dialog
  • Add Feature : manageable height

[0.1.7] - 2020.03.29 #

  • Bug fix

[0.1.6] - 2020.03.29 #

  • Bug fix

[0.1.5] - 2020.03.29 #

  • Replace Stream by valueNotifier

[0.1.4] - 2020.03.29 #

  • Replace Stream by valueNotifier

[0.1.3] - 2020.03.28 #

  • possibility to load filter online once

[0.1.2] - 2020.03.27 #

  • improve performance

[0.1.1] - 2020.03.26 #

  • bloc bug fix

[0.1.0] - 2020.03.25 #

  • bug fix publication

[0.0.1] - 2020.03.24 #

  • First publication

example/lib/main.dart

import 'package:dio/dio.dart';
import 'package:dropdown_search/dropdown_search.dart';
import 'package:flutter/material.dart';

import 'user_model.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      //enable this line if you want test Dark Mode
      //theme: ThemeData.dark(),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("DropdownSearch Demo")),
      body: Padding(
        padding: const EdgeInsets.all(25),
        child: Form(
          key: _formKey,
          autovalidate: true,
          child: ListView(
            padding: EdgeInsets.all(4),
            children: <Widget>[
              ///Menu Mode with no searchBox
              DropdownSearch<String>(
                validator: (v) => v == null ? "required field" : null,
                hint: "Select a country",
                mode: Mode.MENU,
                showSelectedItem: true,
                items: ["Brazil", "Italia (Disabled)", "Tunisia", 'Canada'],
                label: "Menu mode *",
                showClearButton: true,
                onChanged: print,
                popupItemDisabled: (String s) => s.startsWith('I'),
                selectedItem: "Brazil",
              ),
              Divider(),
              DropdownSearch<UserModel>(
                mode: Mode.BOTTOM_SHEET,
                isFilteredOnline: true,
                showClearButton: true,
                showSearchBox: true,
                label: 'User *',
                dropdownSearchDecoration: InputDecoration(
                    filled: true,
                    fillColor:
                        Theme.of(context).inputDecorationTheme.fillColor),
                autoValidate: true,
                validator: (UserModel u) =>
                    u == null ? "user field is required " : null,
                onFind: (String filter) => getData(filter),
                onChanged: (UserModel data) {
                  print(data);
                },
                dropdownBuilder: _customDropDownExample,
                popupItemBuilder: _customPopupItemBuilderExample,
              ),
              Divider(),

              ///custom itemBuilder and dropDownBuilder
              DropdownSearch<UserModel>(
                showSelectedItem: true,
                compareFn: (UserModel i, UserModel s) => i.isEqual(s),
                label: "Person",
                onFind: (String filter) => getData(filter),
                onChanged: (UserModel data) {
                  print(data);
                },
                dropdownBuilder: _customDropDownExample,
                popupItemBuilder: _customPopupItemBuilderExample2,
              ),
              Divider(),

              ///BottomSheet Mode with no searchBox
              DropdownSearch<String>(
                mode: Mode.BOTTOM_SHEET,
                maxHeight: 300,
                items: ["Brazil", "Italia", "Tunisia", 'Canada'],
                label: "Custom BottomShet mode",
                onChanged: print,
                selectedItem: "Brazil",
                showSearchBox: true,
                searchBoxDecoration: InputDecoration(
                  border: OutlineInputBorder(),
                  contentPadding: EdgeInsets.fromLTRB(12, 12, 8, 0),
                  labelText: "Search a country",
                ),
                popupTitle: Container(
                  height: 50,
                  decoration: BoxDecoration(
                    color: Theme.of(context).primaryColorDark,
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(20),
                      topRight: Radius.circular(20),
                    ),
                  ),
                  child: Center(
                    child: Text(
                      'Country',
                      style: TextStyle(
                        fontSize: 24,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
                popupShape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(24),
                    topRight: Radius.circular(24),
                  ),
                ),
              ),
              Divider(),

              ///merge online and offline data in the same list and set custom max Height
              DropdownSearch<UserModel>(
                items: [
                  UserModel(name: "Offline name1", id: "999"),
                  UserModel(name: "Offline name2", id: "0101")
                ],
                maxHeight: 300,
                onFind: (String filter) => getData(filter),
                label: "choose a user",
                onChanged: print,
                showSearchBox: true,
              ),
              Divider(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _customDropDownExample(
      BuildContext context, UserModel item, String itemDesignation) {
    return Container(
      child: (item?.avatar == null)
          ? ListTile(
              contentPadding: EdgeInsets.all(0),
              leading: CircleAvatar(),
              title: Text("No item selected"),
            )
          : ListTile(
              contentPadding: EdgeInsets.all(0),
              leading: CircleAvatar(
                backgroundImage: NetworkImage(item.avatar),
              ),
              title: Text(item.name),
              subtitle: Text(
                item.createdAt.toString(),
              ),
            ),
    );
  }

  Widget _customPopupItemBuilderExample(
      BuildContext context, UserModel item, bool isSelected) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 8),
      decoration: !isSelected
          ? null
          : BoxDecoration(
              border: Border.all(color: Theme.of(context).primaryColor),
              borderRadius: BorderRadius.circular(5),
              color: Colors.white,
            ),
      child: ListTile(
        selected: isSelected,
        title: Text(item.name),
        subtitle: Text(item.createdAt.toString()),
        leading: CircleAvatar(
          backgroundImage: NetworkImage(item.avatar),
        ),
      ),
    );
  }

  Widget _customPopupItemBuilderExample2(
      BuildContext context, UserModel item, bool isSelected) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 8),
      decoration: !isSelected
          ? null
          : BoxDecoration(
              border: Border.all(color: Theme.of(context).primaryColor),
              borderRadius: BorderRadius.circular(5),
              color: Colors.white,
            ),
      child: ListTile(
        selected: isSelected,
        title: Text(item.name),
        subtitle: Text(item.createdAt.toString()),
        leading: CircleAvatar(
          backgroundImage: NetworkImage(item.avatar),
        ),
      ),
    );
  }

  Future<List<UserModel>> getData(filter) async {
    var response = await Dio().get(
      "http://5d85ccfb1e61af001471bf60.mockapi.io/user",
      queryParameters: {"filter": filter},
    );

    var models = UserModel.fromJsonList(response.data);
    return models;
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  dropdown_search: ^0.4.3

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:dropdown_search/dropdown_search.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
81
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
90
Learn more about scoring.

We analyzed this package on Jun 4, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.2
  • pana: 0.13.8-dev
  • Flutter: 1.17.1

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.7.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.12
meta 1.1.8
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test