### Basic Searchfield Widget Setup Source: https://pub.dev/packages/searchfield/example This snippet shows the main structure of a Flutter app using the Searchfield widget. It includes the MyApp and SearchFieldSample widgets, defining the app's theme and the initial setup for the search field. ```dart // import 'package:example/pagination.dart'; import 'package:flutter/material.dart'; import 'package:searchfield/searchfield.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter App', theme: ThemeData( colorSchemeSeed: Colors.indigo, useMaterial3: true, brightness: Brightness.light, ), darkTheme: ThemeData( colorSchemeSeed: Colors.blue, useMaterial3: true, brightness: Brightness.dark, ), home: SearchFieldSample(), debugShowCheckedModeBanner: false, ); } } class SearchFieldSample extends StatefulWidget { const SearchFieldSample({Key? key}) : super(key: key); @override State createState() => _SearchFieldSampleState(); } class _SearchFieldSampleState extends State { @override void initState() { cities = [ City('New York', '10001'), City('Los Angeles', '90001'), City('Chicago', '60601'), City('Houston', '77001'), City('Phoenix', '85001'), City('Philadelphia', '19101'), City('San Antonio', '78201'), City('San Diego', '92101'), City('Dallas', '75201'), City('San Jose', '95101'), City('Austin', '73301'), City('Jacksonville', '32099'), City('Fort Worth', '76101'), City('Columbus', '43201'), City('Charlotte', '28201'), City('San Francisco', '94101'), City('Indianapolis', '46201'), City('Seattle', '98101'), City('Denver', '80201'), City('Washington', '20001'), City('Boston', '02101'), ].map( (City ct) { return SearchFieldListItem( ct.name, value: ct.zip.toString(), item: ct, child: searchChild(ct, isSelected: false), ); }, ).toList(); super.initState(); } Widget searchChild(City city, {bool isSelected = false}) => ListTile( contentPadding: EdgeInsets.all(0), title: Text(city.name, style: TextStyle(color: isSelected ? Colors.green : null)), trailing: Text('#${city.zip}'), ); var cities = >[]; SearchFieldListItem? selectedValue; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Searchfield Demo')), body: Padding( padding: const EdgeInsets.all(8.0), child: Column( mainAxisAlignment: MainAxisAlignment.start, spacing: 20, children: [ TextField( decoration: InputDecoration( labelText: 'Enter username', border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(8)), ), ), ), SearchField( suggestionsDecoration: SuggestionDecoration( borderRadius: BorderRadius.all(Radius.circular(2)), itemPadding: EdgeInsets.symmetric(horizontal: 16), ), maxSuggestionBoxHeight: 300, onSuggestionTap: (SearchFieldListItem item) { setState(() { selectedValue = item; }); }, searchInputDecoration: SearchInputDecoration( hintText: 'Search for a city or zip code', prefixIcon: Icon(Icons.search), suffix: Icon(Icons.expand_more), border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(8)), ), ), onSearchTextChanged: (searchText) { if (searchText.isEmpty) { return cities .map((e) => e.copyWith( child: searchChild(e.item!, isSelected: e == selectedValue))) .toList(); } // filter the list of cities by the search text final filter = List>.from(cities) .where((city) { return city.item!.name .toLowerCase() .contains(searchText.toLowerCase()) || city.item!.zip.toString().contains(searchText); }).toList(); return filter; }, selectedValue: selectedValue, ) ], ), )); } } class City { final String name; final String zip; City(this.name, this.zip); } ``` -------------------------------- ### Initialize Suggestions Source: https://pub.dev/packages/searchfield Initialize a list of suggestions of any type. This example shows initializing a list of 'City' objects. ```dart late List> cities; SearchFieldListItem? selectedValue; @override void initState() { cities = [ City('New York', '10001'), City('Los Angeles', '90001'), ... ] super.initState(); } ``` -------------------------------- ### Load Suggestions from Network with Custom Loading Widget Source: https://pub.dev/packages/searchfield Demonstrates loading suggestions from a network with a custom widget displayed while loading. This example also shows how to filter suggestions based on user input and fetch initial suggestions. ```dart SearchField( onSearchTextChanged: (query) { final filter = suggestions .where((element) => element.toLowerCase().contains(query.toLowerCase())) .toList(); return filter .map((e) => SearchFieldListItem(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(e, child: searchChild(e))) .toList(), focusNode: focus, suggestionState: Suggestion.expand, onSuggestionTap: (SearchFieldListItem x) { }, ), ``` -------------------------------- ### Basic Searchfield Usage (Before v1.2.0) Source: https://pub.dev/packages/searchfield/changelog This example demonstrates the basic usage of the SearchField widget before version 1.2.0, where `initialValue` was used to set the selected value. ```dart SearchField( hint: 'Basic SearchField', dynamicHeight: true, maxSuggestionBoxHeight: 300, initialValue: SearchFieldListItem('ABC'), suggestions: dynamicHeightSuggestion .map(SearchFieldListItem.new) .toList(), suggestionState: Suggestion.expand, ) ``` -------------------------------- ### Map Suggestions to SearchFieldListItem Source: https://pub.dev/packages/searchfield Map your data objects to SearchFieldListItem to configure how they are displayed and searched. This example maps 'City' objects. ```dart @override void initState() { cities = [ City('New York', '10001'), City('Los Angeles', '90001'), ... ].map( (City ct) { return SearchFieldListItem( // 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(); } ``` -------------------------------- ### Searchfield Usage with Explicit SelectedValue Handling (v1.2.0+) Source: https://pub.dev/packages/searchfield/changelog This example shows the updated usage of the SearchField widget from version 1.2.0 onwards, where the `selectedValue` must be explicitly managed by the client using the `onSuggestionTap` callback. ```dart var selectedValue = SearchFieldListItem('ABC'); SearchField( hint: 'Basic SearchField', dynamicHeight: true, maxSuggestionBoxHeight: 300, // now the selectedValue is handled by the client onSuggestionTap: (SearchFieldListItem item) { setState(() { selectedValue = item; }); }, selectedValue: selectedValue, // rename initialValue to selectedValue suggestions: dynamicHeightSuggestion .map(SearchFieldListItem.new) .toList(), suggestionState: Suggestion.expand, ) ``` -------------------------------- ### Declare searchfield in pubspec.yaml Source: https://pub.dev/packages/searchfield/install This is an example of how the searchfield dependency will appear in your pubspec.yaml file after running `flutter pub add searchfield`. ```yaml dependencies: searchfield: ^2.0.0 ``` -------------------------------- ### Migrate SearchField Input Decoration Source: https://pub.dev/packages/searchfield/changelog Shows the transition from direct property usage to the SearchInputDecoration wrapper. ```dart SearchField( textCapitalization: TextCapitalization.words, style: TextStyle(...) ... ) ``` ```dart SearchField( searchInputDecoration: SearchInputDecoration( textCapitalization: TextCapitalization.words, style: TextStyle(...) ... ) ... ), ``` -------------------------------- ### Dynamic Searchfield Suggestions with Filtering Source: https://pub.dev/packages/searchfield Implement dynamic filtering of suggestions based on user input using the 'onSearchTextChanged' callback. This provides real-time search results as the user types. ```dart SearchField( onSearchTextChanged: (query) { final filter = suggestions .where((element) => element.toLowerCase().contains(query.toLowerCase())) .toList(); return filter .map((e) => SearchFieldListItem(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 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(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 x) { setState(() { selectedValue = x.item; }); }, ), ) ``` -------------------------------- ### Customize Suggestion Item Decoration Source: https://pub.dev/packages/searchfield Customize the padding, border radius, and background color of each suggestion item using SuggestionDecoration. ```dart SearchField( hint: 'Search for a city or zip code', maxSuggestionBoxHeight: 300, onSuggestionTap: (SearchFieldListItem 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, ), ), ``` -------------------------------- ### Customize Suggestions List Source: https://pub.dev/packages/searchfield Customize the appearance of the suggestions list using the suggestionsDecoration property. ```dart SearchField( hint: 'Search for a city or zip code', maxSuggestionBoxHeight: 300, onSuggestionTap: (SearchFieldListItem 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)), ), ), ``` -------------------------------- ### SearchField Properties Source: https://pub.dev/packages/searchfield This section details the various properties available for the SearchField widget, allowing for extensive customization of its appearance and behavior. ```APIDOC ## SearchField Widget Properties ### Description Provides a list of configurable properties for the SearchField widget. ### Properties - **animationDuration** (Duration) - Duration for the animation of the suggestions list. - **autoCorrect** (bool) - Defines whether to enable autoCorrect. Defaults to `true`. - **autofocus** (bool) - Defines whether to enable autofocus. Defaults to `false`. - **autoValidateMode** (AutoValidateMode) - Used to enable/disable this form field auto validation and update its error text. Defaults to `AutoValidateMode.disabled`. - **contextMenuBuilder** (FormField) - 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** (TextEditingController) - TextEditing Controller to interact with the searchfield. - **comparator** (Comparator) - Property to filter out the suggestions with a custom logic (Deprecated. Use `onSearchTextChanged` instead). - **dynamicHeight** (bool) - Set to true to opt-in to dynamic height. Defaults to `false` (`itemHeight : 51`). - **emptyWidget** (Widget) - Custom Widget to show when search returns empty Results or when `showEmpty` is true. Defaults to `SizedBox.shrink`. - **enabled** (bool) - Defines whether to enable the searchfield. Defaults to `true`. - **focusNode** (FocusNode) - FocusNode to interact with the searchfield. - **hint** (String) - Hint for the search Input. - **readOnly** (bool) - Defines whether to enable the searchfield. Defaults to `false`. - **selectedValue** (dynamic) - The initial value to be set in searchfield when its rendered, if not specified it will be empty. - **inputType** (TextInputType) - Keyboard Type for SearchField. - **inputFormatters** (List) - Input Formatter for SearchField. - **itemHeight** (double) - Height of each suggestion Item. Defaults to `51.0`. - **keepSearchOnSelection** (bool) - Boolean to keep the search text in the searchfield when a suggestion is selected. Defaults to `false`. - **marginColor** (Color) - Color for the margin between the suggestions. - **maxSuggestionBoxHeight** (double) - Specifies a maximum height for the suggestion box when `dynamicHeight` is set to `true`. - **maxSuggestionsInViewPort** (int) - The max number of suggestions that can be shown in a viewport. - **offset** (Offset) - Suggestion List offset from the searchfield. The top left corner of the searchfield is the origin (0,0). - **onOutSideTap** (VoidCallback) - Callback when the user taps outside the searchfield. - **onSaved** (FormFieldSetter) - An optional method to call with the final value when the form is saved via FormState.save. - **onScroll** (ScrollCallback) - Callback when the suggestion list is scrolled. It returns the current scroll position in pixels and the max scroll position. - **onSearchTextChanged** (ValueChanged) - Callback when the searchfield text changes, it returns the current text in the searchfield. - **onSuggestionTap** (ValueChanged) - Callback when a suggestion is tapped, it returns the tapped value which can be used to set the selectedValue. - **onSubmit** (ValueChanged) - Callback when the searchfield is submitted, it returns the current text in the searchfield. - **onTap** (VoidCallback) - Callback when the searchfield is tapped or brought into focus. - **scrollbarDecoration** (ScrollbarDecoration) - Decoration for the scrollbar. - **scrollController** (ScrollController) - ScrollController to interact with the suggestions list. - **showEmpty** (bool) - Boolean to show/hide the emptyWidget. - **suggestions** (List) - **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** (SuggestionState) - Enum to hide/show the suggestion on focusing the searchfield. Defaults to `SuggestionState.expand`. - **searchStyle** (TextStyle) - TextStyle for the search Input. - **searchInputDecoration** (InputDecoration) - Decoration for the search Input (e.g. to update HintStyle) similar to built-in textfield widget. - **suggestionsDecoration** (BoxDecoration) - Decoration for suggestions List with ability to add box shadow, background color and much more. - **suggestionDirection** (SuggestionDirection) - Direction of the suggestions list. Defaults to `SuggestionDirection.down`. - **suggestionItemDecoration** (BoxDecoration) - Decoration for suggestionItem with ability to add color and gradient in the background. - **SuggestionAction** (SuggestionAction) - Enum to control focus of the searchfield on suggestion tap. - **suggestionStyle** (TextStyle) - Specifies `TextStyle` for suggestions when no child is provided. - **textInputAction** (TextInputAction) - An action the user has requested the text input control to perform through the submit button on the keyboard. - **textCapitalization** (TextCapitalization) - Configures how the platform keyboard will select an uppercase or lowercase keyboard on IOS and Android. - **textAlign** (TextAlign) - Specifies the alignment of the text in the searchfield. Defaults to `TextAlign.start`. ``` -------------------------------- ### Add searchfield Dependency Source: https://pub.dev/packages/searchfield/install Use this command to add the searchfield package to your Flutter project's dependencies. This command automatically updates your pubspec.yaml file. ```bash $ flutter pub add searchfield ``` -------------------------------- ### Add SearchField Widget Source: https://pub.dev/packages/searchfield Integrate the SearchField widget into your widget tree, configuring its behavior and appearance. ```dart SearchField( hint: 'Search for a city or zip code', maxSuggestionBoxHeight: 300, onSuggestionTap: (SearchFieldListItem item) { setState(() { selectedValue = item; }); }, onSearchTextChanged: (searchText) { if (searchText.isEmpty) { return cities } // filter the list with your custom search logic final filter = List>.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, ), ``` -------------------------------- ### Import searchfield Package in Dart Source: https://pub.dev/packages/searchfield/install Import the searchfield package into your Dart code to use its widgets and functionalities. This import statement is required before using any components from the package. ```dart import 'package:searchfield/searchfield.dart'; ``` -------------------------------- ### Implement Searchfield Validation Source: https://pub.dev/packages/searchfield Use the 'validator' property to define custom validation logic for the Searchfield input. Ensure the input matches expected criteria before proceeding. ```dart 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 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) {}, )) ) ``` -------------------------------- ### Customize Search Input Source: https://pub.dev/packages/searchfield Customize the appearance of the search input field using the searchInputDecoration property. ```dart SearchField( hint: 'Search for a city or zip code', maxSuggestionBoxHeight: 300, onSuggestionTap: (SearchFieldListItem 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)), ), ... ), ), ``` -------------------------------- ### Customize Searchfield Suggestions with Widgets Source: https://pub.dev/packages/searchfield Pass custom widgets to the 'child' property of 'SearchFieldListItem' to fully customize the appearance of suggestions. This allows for rich UI elements within the suggestion list. ```dart 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(), ... ... ) ``` -------------------------------- ### City Data Class Source: https://pub.dev/packages/searchfield/example Defines a simple data class to represent a city with its name and zip code. This class is used to structure the data for the autocomplete suggestions. ```dart class City { String name; String zip; City(this.name, this.zip); } ``` -------------------------------- ### Clear Input Button Source: https://pub.dev/packages/searchfield/example Provides a button to clear the currently selected input value in the search field. This is useful for resetting the search. ```dart ElevatedButton( onPressed: () { setState(() { selectedValue = null; }); }, child: Text('clear input')) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.