Flutter搜索自动补全插件search_field_autocomplete的使用

发布于 1周前 作者 bupafengyu 来自 Flutter

Flutter搜索自动补全插件search_field_autocomplete的使用

插件介绍

search_field_autocomplete 是一个为Flutter应用程序提供的可定制化搜索字段插件,支持iOS风格和Material Design风格的搜索字段。它允许用户在输入时显示自动补全建议,并且可以根据需要自定义排序和过滤建议。

示例代码

下面是一个完整的示例代码,展示了如何使用search_field_autocomplete插件实现一个带有自动补全功能的搜索字段。

import 'package:flutter/material.dart';
import 'package:search_field_autocomplete/search_field_autocomplete.dart';

void main() {
  runApp(const Example1());
}

class Example1 extends StatelessWidget {
  const Example1({super.key});

  List<SearchFieldAutoCompleteItem<String>> get suggestions {
    return const [
      SearchFieldAutoCompleteItem<String>(searchKey: 'Apple', value: 'apple', child: Text('1'),
      SearchFieldAutoCompleteItem<String>(searchKey: 'Banana', value: 'banana'),
      SearchFieldAutoCompleteItem<String>(searchKey: 'Cherry', value: 'cherry'),
      SearchFieldAutoCompleteItem<String>(searchKey: 'Date', value: 'date'),
      SearchFieldAutoCompleteItem<String>(searchKey: 'Fig', value: 'fig'),
      SearchFieldAutoCompleteItem<String>(searchKey: 'Grapes', value: 'grapes'),
      SearchFieldAutoCompleteItem<String>(searchKey: 'Kiwi', value: 'kiwi'),
      SearchFieldAutoCompleteItem<String>(searchKey: 'Lemon', value: 'lemon'),
      SearchFieldAutoCompleteItem<String>'Mango', value: 'mango'),
      SearchFieldAutoCompleteItem<String>'Orange', value: 'orange'),
      SearchFieldAutoCompleteItem<String>'Peach', value: 'peach'),
      SearchFieldAutoCompleteItem<String>'Pear', value: 'pear'),
      SearchFieldAutoCompleteItem<String>'Pineapple', value: 'pineapple'),
      SearchFieldAutoCompleteItem<String>'Strawberry', value: 'strawberry'),
      SearchFieldAutoCompleteItem<String>'Watermelon', value: 'watermelon'),
    ];
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      darkTheme: ThemeData.dark(useMaterial3: true),
      themeMode: ThemeMode.dark,
      home: Scaffold(
        appBar: AppBar(title: const Text('SearchField AutoComplete Example')),
        body: Center(
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: SearchFieldAutoComplete<String>(
              placeholder: 'Search fruits',
              suggestions: suggestions,
              suggestionsDecoration: SuggestionDecoration(
                marginSuggestions: const EdgeInsets.all(8.0),
                color: Colors.greenAccent,
                borderRadius: BorderRadius.circular(16.0),
              ),
              onSuggestionSelected: (selectedItem) {
                print("selected: ${selectedItem.searchKey}");
              },
              suggestionItemBuilder: (context, searchFieldItem) {
                return Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text(
                    searchFieldItem.searchKey,
                    style: TextStyle(color: Colors.blueGrey.shade900),
                  ),
                );
              },
            ),
          ),
        ),
      ),
    );
  }
}

更多关于Flutter搜索自动补全插件search_field_autocomplete的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter搜索自动补全插件search_field_autocomplete的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter项目中使用search_field_autocomplete插件来实现搜索自动补全功能的代码示例。这个插件可以帮助你创建一个带有自动补全功能的搜索栏。

首先,确保你已经将search_field_autocomplete插件添加到了你的pubspec.yaml文件中:

dependencies:
  flutter:
    sdk: flutter
  search_field_autocomplete: ^0.4.0  # 请确保使用最新版本

然后运行flutter pub get来安装依赖。

接下来,在你的Dart文件中(比如main.dart),你可以按照以下步骤来实现搜索自动补全功能:

import 'package:flutter/material.dart';
import 'package:search_field_autocomplete/search_field_autocomplete.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Search Field Autocomplete Example'),
        ),
        body: SearchFieldAutocompleteExample(),
      ),
    );
  }
}

class SearchFieldAutocompleteExample extends StatefulWidget {
  @override
  _SearchFieldAutocompleteExampleState createState() => _SearchFieldAutocompleteExampleState();
}

class _SearchFieldAutocompleteExampleState extends State<SearchFieldAutocompleteExample> {
  final List<String> suggestions = List.generate(20, (i) => "Suggestion $i");

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: SearchFieldAutocomplete<String>(
        key: ValueKey('search_field_autocomplete'),
        decoration: InputDecoration(
          prefixIcon: Icon(Icons.search),
          labelText: 'Search',
          suffixIcon: IconButton(
            icon: Icon(Icons.clear),
            onPressed: () {
              // 清除搜索框内容
              _controller.clear();
              _focusNode.unfocus();
            },
          ),
        ),
        keyboardType: TextInputType.text,
        textController: _controller,
        focusNode: _focusNode,
        suggestionsCallback: (query) async {
          // 模拟异步获取建议
          await Future.delayed(Duration(milliseconds: 300));
          return suggestions.where((suggestion) =>
              suggestion.toLowerCase().contains(query.toLowerCase())
          ).toList();
        },
        onSelected: (suggestion) {
          // 用户选择建议时的回调
          print("Selected: $suggestion");
        },
        clearIcon: Icon(Icons.clear),
        optionsViewBuilder: (context, state) {
          return Material(
            elevation: 4.0,
            child: state.when(
              loading: () => Center(child: CircularProgressIndicator()),
              error: (error) => Center(child: Text("Error: $error")),
              empty: () => Center(child: Text("No suggestions")),
              suggestions: (suggestions) => ListView.builder(
                itemCount: suggestions.length,
                itemBuilder: (context, index) {
                  final suggestion = suggestions[index];
                  return ListTile(
                    leading: Icon(Icons.arrow_forward),
                    title: Text(suggestion),
                    onTap: () {
                      state.selectSuggestion(suggestion);
                    },
                  );
                },
              ),
            ),
          );
        },
      ),
    );
  }

  final TextEditingController _controller = TextEditingController();
  final FocusNode _focusNode = FocusNode();

  @override
  void dispose() {
    _controller.dispose();
    _focusNode.dispose();
    super.dispose();
  }
}

在这个示例中:

  1. 我们创建了一个SearchFieldAutocomplete组件,它包含了搜索栏和建议列表。
  2. suggestionsCallback函数模拟了一个异步获取建议的过程,它会返回符合查询条件的建议列表。
  3. onSelected函数会在用户选择一个建议时被调用。
  4. optionsViewBuilder函数用于自定义建议列表的UI。

你可以根据需要进一步自定义这个示例,比如从服务器获取建议数据、调整UI样式等。希望这个示例能帮到你!

回到顶部