搜索插件、代码仓与 APP 分类

searchfield 封面
插件详情v2.0.0

searchfield

一个高度可定制、简单易用的自动完成小部件,适用于您的 Flutter 应用

AndroidiOSWebmacOSWindowsLinux
近 30 天下载
2.1万
喜欢数
393
Pub 分数
150

安装插件

flutter pub add searchfield

插件介绍

基于插件公开信息、社区数据与项目使用情况整理的选型参考。

SearchField 是一个可自定义且直观的 Flutter AutoComplete 小部件,旨在简化应用程序中的搜索功能。它提供了一种简洁、易于集成的解决方案,可在用户输入时过滤并显示建议。支持所有主要平台——包括 Android、iOS、Web、macOS、Windows 和 Linux,确保在所有平台上行为一致。该包强调简单性,同时不牺牲灵活性,使开发者能够根据需求定制 UI 和行为。

适合场景

  • 列表中的实时搜索
  • 带建议下拉列表的表单输入
  • 数据密集型应用中的增强用户体验
  • 动态过滤大型数据集
  • 表单的可自定义自动完成
  • 跨平台搜索组件

主要特点

  • 高度可定制的外观
  • 实时过滤
  • 对多平台的支持
  • 简单的 API,设置简单
  • 可扩展以支持自定义逻辑
  • 内置键盘和焦点管理

适合对象

  • 开发搜索密集型应用的开发者
  • 注重跨平台一致性的团队
  • 需要轻量级自动补全解决方案的项目
  • 具有动态输入的面向用户界面的应用程序
  • 通过交互式搜索实现快速原型设计

使用建议

  • 可能需要额外的样式设置以实现复杂设计
  • 使用非常大的数据集时,性能取决于实现方式
  • 有限的内置验证功能
  • 不适用于超出文本匹配的高级筛选
  • 自定义渲染需要了解 Flutter widget

原始 README

以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。

searchfield: ^2.0.0

Flutter Platform Badge Pub Prerelease codecov Build MIT License Badge Sponsor @maheshj01

⭐️Show some ❤️ and star the repo.⭐

Frame 1 (1)

A highly customizable, simple and easy to use AutoComplete widget for your Flutter app. This widget allows you to

  • search 🔍 and select from a list of suggestions
  • validate the input with custom validation logic.
  • Dynamic height of each suggestion item.
  • show suggestions as a custom widget
  • Map a custom value to the suggestion list item.
  • lazy load the suggestions from Network with custom Loading widget
  • show dynamic suggestions above or below the input field
  • define max number of items visible in the viewport 📱
  • filter out the suggestions with a custom logic
  • visually customize the input and the suggestions
  • navigate through the suggestions using keyboard for Desktop 🖥 ️
  • Listen to scroll events of suggestions

Getting Started

Installation
  • Add the dependency
flutter pub add searchfield
  • Import the package
import 'package:searchfield/searchfield.dart';

Use the Widget in three steps

see complete code here

Step 1: Initialize your suggestions of any Type
  late List<SearchFieldListItem<City>> cities;
  SearchFieldListItem<City>? selectedValue;

  @override
  void initState() {
    cities = [
      City('New York', '10001'),
      City('Los Angeles', '90001'),
      ...
    ]
    super.initState();
  }
Step 2: Map the suggestions to SearchFieldListItem

see SearchFieldListItem to know more about the properties

 @override
  void initState() {
    cities = [
      City('New York', '10001'),
      City('Los Angeles', '90001'),
      ...
    ].map(
      (City ct) {
        return SearchFieldListItem<City>(
          // search will be performed on this value
          ct.name,
          // value to set in input on click, defaults to searchKey (optional)
          value: ct.zip.toString(),
          // custom object to pass in the suggestion list (optional)
          item: ct,
          // custom widget to show in the suggestion list (optional)
          child: searchChild(ct, isSelected: false),
        );
      },
    ).toList();
    super.initState();
  }
Step 3: Add SearchField to your widget tree
 SearchField(
    hint: 'Search for a city or zip code',
    maxSuggestionBoxHeight: 300,
    onSuggestionTap: (SearchFieldListItem<City> item) {
      setState(() {
        selectedValue = item;
      });
    },
    onSearchTextChanged: (searchText) {
      if (searchText.isEmpty) {
        return cities
      }
      // filter the list with your custom search logic
      final filter = List<SearchFieldListItem<City>>.from(cities)
          .where((city) {
        return city.item!.name
                .toLowerCase()
                .contains(searchText.toLowerCase()) ||
            city.item!.zip.toString().contains(searchText);
      }).toList();
      return filter;
    },
    selectedValue: selectedValue,
    suggestions: cities,
    suggestionState: Suggestion.expand,
  ),

Customizing the Search Input

 SearchField(
    hint: 'Search for a city or zip code',
    maxSuggestionBoxHeight: 300,
    onSuggestionTap: (SearchFieldListItem<City> item) {
      setState(() {
        selectedValue = item;
      });
    },
    selectedValue: selectedValue,
    ...
    /// customize the search input with wide range of properties
    /// through SearchInputDecoration
    searchInputDecoration: SearchInputDecoration(
      prefixIcon: Icon(Icons.search),
      suffix: Icon(Icons.expand_more),
      border: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(8)),
      ),
      ...
    ),
  ),

Customizing the Suggestions List

 SearchField(
    hint: 'Search for a city or zip code',
    maxSuggestionBoxHeight: 300,
    onSuggestionTap: (SearchFieldListItem<City> item) {
      setState(() {
        selectedValue = item;
      });
    },
    selectedValue: selectedValue,
    ...
    /// customize the decoration of the suggestions list
    suggestionsDecoration: SuggestionDecoration(
      border: Border.all(color: Colors.grey),
      hoverColor: Colors.grey.shade200,
      borderRadius: BorderRadius.all(Radius.circular(2)),
    ),
  ),

Customizing the Suggestions Item

 SearchField(
    hint: 'Search for a city or zip code',
    maxSuggestionBoxHeight: 300,
    onSuggestionTap: (SearchFieldListItem<City> item) {
      setState(() {
        selectedValue = item;
      });
    },
    selectedValue: selectedValue,
    ...
    /// customizes the decoration of each suggestion item
    suggestionItemDecoration: SuggestionDecoration(
      padding: EdgeInsets.all(8),
      borderRadius: BorderRadius.all(Radius.circular(2)),
      color: Colors.grey.shade200,
    ),
  ),
Example 2 (Network demo)

Ability to load suggestions from the network with a custom loading widget

SearchField(
    onSearchTextChanged: (query) {
    final filter = suggestions
        .where((element) =>
            element.toLowerCase().contains(query.toLowerCase()))
        .toList();
    return filter
        .map((e) =>
            SearchFieldListItem<String>(e, child: searchChild(e)))
        .toList();
    },
    onTap: () async {
    final result = await getSuggestions();
    setState(() {
        suggestions = result;
    });
    },
    /// widget to show when suggestions are empty
    emptyWidget: Container(
        decoration: suggestionDecoration,
        height: 200,
        child: const Center(
            child: CircularProgressIndicator(
        color: Colors.white,
        ))),
    hint: 'Load suggestions from network',
    itemHeight: 50,
    scrollbarDecoration: ScrollbarDecoration(),
    suggestionStyle: const TextStyle(fontSize: 24, color: Colors.white),
    searchInputDecoration: SearchInputDecoration(...),
    border: OutlineInputBorder(...)
    fillColor: Colors.white,
    filled: true,
    contentPadding: const EdgeInsets.symmetric(
        horizontal: 20,
    )),
    suggestionsDecoration: suggestionDecoration,
    suggestions: suggestions
        .map((e) => SearchFieldListItem<String>(e, child: searchChild(e)))
        .toList(),
    focusNode: focus,
    suggestionState: Suggestion.expand,
    onSuggestionTap: (SearchFieldListItem<String> x) {

    },
),
Example 3 Custom Widgets

complete code here

demo-ezgif com-video-to-gif-converter (1)

Example 4 Load suggestions from network with Pagination

Note that this also maintains the Scroll position when new items are added to list see: complete code here

output_video-ezgif com-video-to-gif-converter

Example 5 (Validation)
Form(
  key: _formKey,
  child: SearchField(
    suggestions: _statesOfIndia
        .map((e) => SearchFieldListItem(e))
        .toList(),
    suggestionState: Suggestion.expand,
    textInputAction: TextInputAction.next,
    hint: 'SearchField Example 2',
    searchStyle: TextStyle(
      fontSize: 18,
      color: Colors.black.withValues(alpha: 0.8),
    ),
    validator: (x) {
      if (!_statesOfIndia.contains(x) || x!.isEmpty) {
        return 'Please Enter a valid State';
      }
      return null;
    },
    selectedValue: selectedValue,
      onSuggestionTap: (SearchFieldListItem<Country> x) {
        setState(() {
          selectedValue = x.item;
        });
      },
    searchInputDecoration: SearchInputDecoration(
      focusedBorder: OutlineInputBorder(
        borderSide: BorderSide(
          color: Colors.black.withValues(alpha: 0.8),
        ),
      ),
      border: OutlineInputBorder(
        borderSide: BorderSide(color: Colors.red),
      ),
    ),
    maxSuggestionsInViewPort: 6,
    itemHeight: 50,
    onTap: (x) {},
  ))
 SearchField(
    onSearchTextChanged: (query) {
      final filter = suggestions
          .where((element) =>
              element.toLowerCase().contains(query.toLowerCase()))
          .toList();
      return filter
          .map((e) => SearchFieldListItem<String>(e,
              child: Padding(
                padding: const EdgeInsets.symmetric(vertical: 4.0),
                child: Text(e,
                    style: TextStyle(fontSize: 24, color: Colors.red)),
              )))
          .toList();
    },
    selectedValue: selectedValue,
      onSuggestionTap: (SearchFieldListItem<Country> x) {
        setState(() {
          selectedValue = x.item;
        });
      },
    key: const Key('searchfield'),
    hint: 'Search by country name',
    itemHeight: 50,
    searchInputDecoration:
        SearchInputDecoration(hintStyle: TextStyle(color: Colors.red)),
    suggestionsDecoration: SuggestionDecoration(
        padding: const EdgeInsets.all(4),
        border: Border.all(color: Colors.red),
        borderRadius: BorderRadius.all(Radius.circular(10))),
    suggestions: suggestions
        .map((e) => SearchFieldListItem<String>(e,
            child: Padding(
              padding: const EdgeInsets.symmetric(vertical: 4.0),
              child: Text(e,
                  style: TextStyle(fontSize: 24, color: Colors.red)),
            )))
        .toList(),
    focusNode: focus,
    suggestionState: Suggestion.expand,
    selectedValue: selectedValue,
    onSuggestionTap: (SearchFieldListItem<String> x) {
      setState(() {
          selectedValue = x.item;
        });
    },
  ),

Customize the suggestions the way you want

Suggestions can be passed as a widget using the child property of SearchFieldListItem

SearchField(
  suggestions: _statesOfIndia
     .map((e) => SearchFieldListItem(e,
        child: Align(
          alignment: Alignment.centerRight,
          child: Padding(
             padding: const EdgeInsets.symmetric(horizontal:16.0),
               child: Text(e,
                 style: TextStyle(color: Colors.red),
               ),
             ),
          ))).toList(),
    ...
    ...
)
Support for Keyboard Navigation

With v0.9.5 Searchfield now adds support for Keyboard navigation, you can now navigate through the suggestions using the keyboard.

Shortcuts:

  • Up/Down Arrow keys are circular, i.e. if you reach the last item and press down, it will take you to the first item. Similarly, if you reach the first item and press up, it will take you to the last item.
  • ctr/option + down to scroll to last item in the list
  • ctr/option + up to scroll to first item in the list
Support for Dynamic positioning of suggestions

The position of suggestions is dynamic based on the space available for the suggestions to expand within the viewport.

SearchFieldListItem

SearchFieldListItem is a generic class that is used to create the suggestions list. It takes a searchKey and an optional value and item which can be used to pass a custom object to the suggestion list.

  • searchKey required: This value is used to search the list, and will be shown in the suggestions list and also shown in input field when a suggestion is selected.
  • value optional: The value to set in the input on suggestion click,if not specified searchKey will be used
  • item optional: The custom object to pass in the suggestion list, this can be used to show a value different from the searchKey in the suggestion list.
  • child optional: The custom widget to show in the suggestion list, this can be used to pass a custom widget to the suggestion list.

Properties

  • animationDuration: Duration for the animation of the suggestions list.
  • autoCorrect: Defines whether to enable autoCorrect defaults to true
  • autofocus: Defines whether to enable autofocus defaults to false
  • autoValidateMode: Used to enable/disable this form field auto validation and update its error text.defaults to AutoValidateMode.disabled
  • contextmenubuilder: Creates a [FormField] that contains a [TextField]. When a [controller] is specified, [initialValue] must be null (the default). If [controller] is null, then a [TextEditingController] will be constructed automatically and its text will be initialized to [initialValue] or the empty string. For documentation about the various parameters, see the [TextField] class and [TextField.new], the constructor.
  • controller: TextEditing Controller to interact with the searchfield.
  • comparator property to filter out the suggestions with a custom logic (Comparator is deprecated Use onSearchTextChanged instead).
  • dynamicHeight: Set to true to opt-in to dynamic height, defaults to false (itemHeight : 51)
  • emptyWidget: Custom Widget to show when search returns empty Results or when showEmpty is true. (defaults to SizedBox.shrink)
  • enabled: Defines whether to enable the searchfield defaults to true
  • focusNode : FocusNode to interact with the searchfield.
  • hint : hint for the search Input.
  • readOnly : Defines whether to enable the searchfield defaults to false
  • selectedValue : The initial value to be set in searchfield when its rendered, if not specified it will be empty.
  • inputType: Keyboard Type for SearchField
  • inputFormatters: Input Formatter for SearchField
  • itemHeight : height of each suggestion Item, (defaults to 51.0).
  • keepSearchOnSelection: Boolean to keep the search text in the searchfield when a suggestion is selected. Defaults to false.
  • marginColor : Color for the margin between the suggestions.
  • maxSuggestionBoxHeight: Specifies a maximum height for the suggestion box when dynamicHeight is set to true.
  • maxSuggestionsInViewPort : The max number of suggestions that can be shown in a viewport.
  • offset : suggestion List offset from the searchfield, The top left corner of the searchfield is the origin (0,0).
  • onOutSideTap : callback when the user taps outside the searchfield.
  • onSaved : An optional method to call with the final value when the form is saved via FormState.save.
  • onScroll : callback when the suggestion list is scrolled. It returns the current scroll position in pixels and the max scroll position.
  • onSearchTextChanged: callback when the searchfield text changes, it returns the current text in the searchfield.
  • onSuggestionTap : callback when a sugestion is tapped, it returns the tapped value which can be used to set the selectedValue.
  • onSubmit : callback when the searchfield is submitted, it returns the current text in the searchfield.
  • onTap: callback when the searchfield is tapped or brought into focus.
  • scrollbarDecoration: decoration for the scrollbar.
  • scrollController: ScrollController to interact with the suggestions list.
  • showEmpty: Boolean to show/hide the emptyWidget.
  • suggestions(required) : List of SearchFieldListItem to search from. each SearchFieldListItem in the list requires a unique searchKey, which is used to search the list and an optional Widget, Custom Object to display custom widget and to associate a object with the suggestion list.
  • suggestionState: enum to hide/show the suggestion on focusing the searchfield defaults to SuggestionState.expand.
  • searchStyle : textStyle for the search Input.
  • searchInputDecoration : decoration for the search Input (e.g to update HintStyle) similar to built in textfield widget.
  • suggestionsDecoration : decoration for suggestions List with ability to add box shadow background color and much more.
  • suggestionDirection : direction of the suggestions list, defaults to SuggestionDirection.down.
  • suggestionItemDecoration : decoration for suggestionItem with ability to add color and gradient in the background.
  • SuggestionAction : enum to control focus of the searchfield on suggestion tap.
  • suggestionStyle:Specifies TextStyle for suggestions when no child is provided.
  • textInputAction : An action the user has requested the text input control to perform throgh the submit button on keyboard.
  • textCapitalization : Configures how the platform keyboard will select an uppercase or lowercase keyboard on IOS and Android.
  • textAlign: specifies the alignment of the text in the searchfield. Defaults to TextAlign.start.
You can find all the code samples here
Contributing

You are welcome to contribute to this package, to contribute please read the contributing guidelines.

Contributors

Thanks to all the contributors who have helped in improving this package.

Support

If you like this package, consider supporting it by Sponsorship or Donation through github sponsors here

所属分类

源码仓库

使用此插件的项目