기본적인 드롭다운 버튼을 검색 기능, 텍스트 입력 및 자동 완성 기능으로 강화하는 사용자 정의 가능한 플러터 패키지입니다. 드롭다운 버튼, 텍스트 필드, 자동 완성의 기능을 하나의 유연한 위젯으로 통합했습니다. 실시간 필터링과 사용자 입력 지원이 필요한 검색 가능한 드롭다운을 필요로 하는 양식에 이상적입니다. 이 패키지는 Android, iOS, 웹, macOS, Windows, Linux 등 모든 주요 플랫폼에서 호환됩니다.
사용 사례
검색 가능한 옵션을 가진 폼 입력
필터링을 통한 동적 데이터 선택
데이터 입력에서 사용자 경험 향상
실시간 제안을 위한 API 통합
앱용 사용자 정의 가능한 드롭다운 UI
기본 드롭다운을 고급 기능으로 대체하기
주요 기능
실시간 필터링이 가능한 검색 가능한 드롭다운
사용자 정의 스타일 및 테마 지원
통합 텍스트 입력 및 검증
사용자 입력을 기반으로 한 자동 제안
DropdownButton 및 TextFormField 확장
크로스 플랫폼 호환성
적합한 대상
양식 중심 애플리케이션을 개발하는 개발자
동적이고 검색 가능한 선택이 필요한 앱
데이터 입력에서 사용자 경험을 우선시하는 팀
경량이지만 강력한 드롭다운을 필요로 하는 프로젝트
Flutter 초보자가 고급 위젯 탐색 중
고려 사항
성능 문제를 방지하기 위해 대규모 데이터 세트를 신중하게 처리해야 합니다
비동기 데이터 로딩을 위한 추가 로직이 필요할 수 있습니다
스타일 맞춤화는 Flutter의 테마 시스템에 대한 이해가 필요합니다
기본 검증을 넘어서는 제한된 내장 오류 처리
상호작용이 없는 드롭다운 사용 사례에는 적합하지 않습니다
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
Flutter DropDownSearchField
A powerful and highly customizable DropDownSearchField (autocomplete) widget for Flutter that supports flat lists, multi-selection, and hierarchical nested data structures. Perfect for categories, organizational structures, file systems, or any data with parent-child relationships.
Key Features:
🔍 Smart Autocomplete - Type-ahead search with debouncing and filtering
🌳 Nested/Hierarchical Dropdowns - Support for unlimited nesting levels with expand/collapse
🏷️ Multi-Selection - Select multiple items with chip display and custom logic
📱 Highly Customizable - Extensive styling and behavior customization options
⚡ Performance Optimized - Pagination support and efficient rendering for large datasets
Features
Core Functionality
Floating Overlay: Displays suggestions in a floating overlay above other widgets
Customizable Appearance: Full customization of suggestion appearance using builder functions
TextField Integration: Supports all standard TextField parameters including decoration, controllers, and styling
Form Support: Available as both standalone widget and FormField with validation
Highly Configurable: Extensive customization options for suggestion box decoration, loading states, animations, debounce duration, and more
Advanced Features
Multi-Select Dropdown: Select multiple items with chip display and custom selection logic
Nested/Hierarchical Dropdown: Support for multi-level nested data structures with expand/collapse functionality
Paginated Suggestions: Load suggestions in batches for improved performance with large datasets
Disabled Items: Mark specific items as non-selectable while keeping them visible
Smart Search: Intelligent filtering with support for nested item searching and auto-expansion
Nested Dropdown Capabilities
Hierarchical Data Structure: Display data in tree-like structures with unlimited nesting levels
Expand/Collapse Controls: Interactive expand/collapse icons for parent items
Multi-Level Selection: Select items at any level of the hierarchy
Auto-Expansion: Automatic expansion when searching through nested items
Customizable Indentation: Configurable child item indentation for visual hierarchy
Parent/Child Selection Logic: Control whether parent items are selectable or just organizational
Smart Filtering: Search functionality that shows matching branches and auto-expands relevant sections
Note: As for DropDownSearchField 1.X this package is based on Dart 3.0 (null-safety). You may also want to explore the new built in Flutter 2 widgets that have similar behavior.
In the code above, the textFieldConfiguration property allows us to
configure the displayed TextField as we want. In this example, we are
configuring the autofocus, style and decoration properties.
The suggestionsCallback is called with the search string that the user
types, and is expected to return a List of data either synchronously or
asynchronously. In this example, we are calling an asynchronous function
called BackendService.getSuggestions which fetches the list of
suggestions.
The itemBuilder is called to build a widget for each suggestion.
In this example, we build a simple ListTile that shows the name and the
price of the item. Please note that you shouldn't provide an onTap
callback here. The DropDownSearchField widget takes care of that.
The onSuggestionSelected is a callback called when the user taps a
suggestion. In this example, when the user taps a
suggestion, we navigate to a page that shows us the information of the
tapped product.
Example 2:
Here's another example, where we use the DropDownSearchFormField inside a Form:
In the textFieldConfiguration, we assign the _dropDownSearchController to
the controller property. This controller is a TextEditingController.
When a suggestion is selected, we utilize the onSuggestionSelected callback
to update the value of the TextField with the selected suggestion.
The validator callback serves a similar purpose as any FormField.validator function.
In our specific example, it verifies whether a value has been entered and displays
an error message if it hasn't. The onSaved callback is employed to store the field's
value in the _selectedFruit member variable.
With the transitionBuilder, we have the flexibility to customize the animation
of the suggestion box. In the given illustration, we immediately return the
suggestionsBox without any animation.
Alternative Layout Architecture:
By default, DropDownSearchField uses a ListView to render the items created by itemBuilder.
If you specify a layoutArchitecture component, it will use this component instead. For example,
here's how we render the items in a grid using the standard GridView:
Placing DropDownSearchField in widgets with animations may cause the suggestions box
to resize incorrectly. Since animation times are variable, this has to be
corrected manually at the end of the animation. You will need to add a
SuggestionsBoxController described below and the following code for the
AnimationController.
There is a known issue with opening dialogs where the suggestions box will sometimes appear too small.
This is a timing issue caused by the animations described above. Currently, showDialog has a duration
of 150 ms for the animations. DropDownSearchField has a delay of 170 ms to compensate for this. Until
the end of the animation can be properly detected and fixed using the solution above, this temporary fix
will work most of the time. If the suggestions box is too small, closing and reopening the keyboard will
usually fix the issue.
Nested Dropdown Feature Guide
The nested dropdown functionality allows you to display hierarchical data in an intuitive tree-like structure. This is perfect for categories, organizational structures, file systems, or any data with parent-child relationships.
Key Concepts
NestedItem Model
The NestedItem<T> class is the core of the nested dropdown system:
NestedItem<String>(
value: 'parentId', // Unique identifier
label: 'Display Name', // Optional display text
icon: Icons.folder, // Optional icon
children: [ // Child itemsNestedItem(value: 'child1', label: 'Child 1'),
NestedItem(value: 'child2', label: 'Child 2'),
],
isExpanded: false, // Expansion state
isSelectable: true, // Can be selected
isDisabled: false, // Is disabled
metadata: {'key': 'value'}, // Custom data
)
Configuration Options
NestedDropdownConfiguration
Configure the behavior and appearance of your nested dropdown:
NestedDropdownConfiguration(
// Visual settings
childIndentation: 16.0, // Indentation per level
showExpandIcons: true, // Show expand/collapse icons
expandIcon: Icons.expand_more, // Custom expand icon
collapseIcon: Icons.expand_less,// Custom collapse icon// Behavior settings
allowParentSelection: true, // Can select parent items
autoExpandOnSearch: true, // Auto-expand when searching
collapseOnOpen: false, // Collapse all on open
initiallyExpanded: false, // Expand all initially
showOnlyMatchingBranches: true, // Show only matching items
)
Advanced Features
Smart Selection Logic
Handle parent-child relationships in multi-select mode:
onNestedSuggestionMultiSelected: (item, isSelected) {
if (isSelected) {
// Select the item
selectedItems.add(item);
// Auto-select all children when parent is selectedif (item.hasChildren) {
selectedItems.addAll(item.selectableDescendants);
}
} else {
// Deselect the item
selectedItems.remove(item);
// Auto-deselect all children when parent is deselectedif (item.hasChildren) {
for (final child in item.selectableDescendants) {
selectedItems.removeWhere((i) => i.value == child.value);
}
}
}
}
Recursive Search: Searches through all hierarchy levels
Utility Methods
The NestedItem class provides helpful utility methods:
final item = NestedItem(...);
// Check propertiesbool hasChildren = item.hasChildren;
bool isLeaf = item.isLeaf;
// Expansion control
item.expand(); // Expand this item
item.collapse(); // Collapse this item
item.expand(recursive: true); // Expand recursively
item.toggleExpansion(); // Toggle expansion state// Find itemsfinal found = item.findByValue('targetValue');
final allDescendants = item.allDescendants;
final selectableOnly = item.selectableDescendants;
// Create copiesfinal copy = item.copyWith(
label: 'New Label',
isExpanded: true,
);
Best Practices
Performance: For large datasets, implement lazy loading in nestedSuggestionsCallback
UX: Use meaningful icons and labels to help users understand hierarchy
Accessibility: Test with screen readers and keyboard navigation
Consistency: Maintain consistent indentation and styling across levels
Feedback: Provide visual feedback for expand/collapse actions
Customizations
DropDownSearchField widgets consist of a TextField and a suggestion box that shows
as the user types. Both are highly customizable
Customizing the TextField
You can customize the text field using the textFieldConfiguration property.
You provide this property with an instance of TextFieldConfiguration,
which allows you to configure all the usual properties of TextField, like
decoration, style, controller, focusNode, autofocus, enabled,
etc.
Customizing the suggestions box
DropDownSearchField provides default configurations for the suggestions box. You can,
however, override most of them. This is done by passing a SuggestionsBoxDecoration
to the suggestionsBoxDecoration property.
Use the offsetX property in SuggestionsBoxDecoration to shift the suggestions box along the x-axis.
You may also pass BoxConstraints to constraints in SuggestionsBoxDecoration to adjust the width
and height of the suggestions box. Using the two together will allow the suggestions box to be placed
almost anywhere.
Customizing the loader, the error and the "no items found" message
You can use the loadingBuilder, errorBuilder and noItemsFoundBuilder to
customize their corresponding widgets. For example, to show a custom error
widget:
By default, the suggestions box will maintain the old suggestions while new
suggestions are being retrieved. To show a circular progress indicator
during retrieval instead, set keepSuggestionsOnLoading to false.
Hiding the suggestions box
There are three scenarios when you can hide the suggestions box.
Set hideOnLoading to true to hide the box while suggestions are being
retrieved. This will also ignore the loadingBuilder. Set hideOnEmpty
to true to hide the box when there are no suggestions. This will also ignore
the noItemsFoundBuilder. Set hideOnError to true to hide the box when there
is an error retrieving suggestions. This will also ignore the errorBuilder.
By default, the suggestions box will automatically hide when the keyboard is hidden.
To change this behavior, set hideSuggestionsOnKeyboardHide to false.
Customizing the decoration of the suggestions box
You can also customize the decoration of the suggestions box using the
suggestionsBoxDecoration property. For example, to remove the elevation
of the suggestions box, you can write:
The suggestions box does not fire for each character the user types. Instead,
we wait until the user is idle for a duration of time, and then call the
suggestionsCallback. The duration defaults to 300 milliseconds, but can be
configured using the debounceDuration parameter.
Customizing the animation
You can customize the suggestion box animation through 3 parameters: the
animationDuration, the animationStart, and the transitionBuilder.
The animationDuration specifies how long the animation should take, while the
animationStart specified what point (between 0.0 and 1.0) the animation
should start from. The transitionBuilder accepts the suggestionsBox and
animationController as parameters, and should return a widget that uses
the animationController to animate the display of the suggestionsBox.
For example:
This uses FadeTransition
to fade the suggestionsBox into the view. Note how the
animationController was provided as the parent of the animation.
In order to fully remove the animation, transitionBuilder should simply
return the suggestionsBox. This callback could also be used to wrap the
suggestionsBox with any desired widgets, not necessarily for animation.
Customizing the offset of the suggestions box
By default, the suggestions box is displayed 5 pixels below the TextField.
You can change this by changing the suggestionsBoxVerticalOffset property.
Customizing the direction of the suggestions list
By default, the suggestions list expands downwards. However, you can customize the growth direction
by using the direction property. It allows you to choose between AxisDirection.down or AxisDirection.up.
If you set it to AxisDirection.up, the list will grow in an upward direction. This means that the first
suggestion will be positioned at the bottom of the list, while the last suggestion will appear at the top.
By setting the autoFlipDirection property to true, the suggestions list will automatically flip
its direction whenever it detects insufficient space in the current direction. This feature is
particularly beneficial when the DropDownSearchField is placed within a scrollable widget or when
the developer wants to ensure that the list is always visible regardless of the user's screen size.
Controlling the suggestionsBox
You can manually control the suggestions box by creating a SuggestionsBoxController instance and
assigning it to the suggestionsBoxController property. This enables you to have control over opening,
closing, toggling, or resizing the suggestions box as per your requirements.
You can also customize suggestion box scroll bar by using property called scrollBarDecoration inside suggestionsBoxDecoration. This allows you to control color, thickness, margin and more.