Flutter自动补全文本插件autocomplete_textfield_ns的使用

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

Flutter自动补全文本插件autocomplete_textfield_ns的使用

autocomplete_textfield_ns 是一个用于Flutter应用的自动补全文本输入框插件。它支持自定义数据类型的建议,并提供了灵活的过滤和排序功能。

插件简介

该插件允许开发者创建一个带有自动完成功能的文本输入框,用户在输入时会根据提供的数据列表显示匹配项。这在需要快速选择或查找特定条目时非常有用。

使用方法

基本设置

首先,确保你已经在pubspec.yaml文件中添加了autocomplete_textfield_ns依赖:

dependencies:
  flutter:
    sdk: flutter
  autocomplete_textfield_ns: ^1.0.0 # 确保版本号正确

然后运行 flutter pub get 来安装这个包。

示例代码

以下是一个完整的示例,展示了如何使用autocomplete_textfield_ns来实现简单的和复杂的自动补全文本输入框。

主入口

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Auto Complete TextField Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

主页面

class MyHomePage extends StatefulWidget {
  [@override](/user/override)
  State<StatefulWidget> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Widget> pages = [FirstPage(), SecondPage()];
  int selectedIndex = 0;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: BottomNavigationBar(
        items: [
          BottomNavigationBarItem(icon: Icon(Icons.looks_one), label: "Simple Use"),
          BottomNavigationBarItem(icon: Icon(Icons.looks_two), label: "Complex Use"),
        ],
        onTap: (index) => setState(() {
          selectedIndex = index;
        }),
        currentIndex: selectedIndex,
      ),
      body: pages[selectedIndex],
    );
  }
}

简单用法页面

class FirstPage extends StatefulWidget {
  [@override](/user/override)
  _FirstPageState createState() => _FirstPageState();
}

class _FirstPageState extends State<FirstPage> {
  List<String> added = [];
  String currentText = "";
  GlobalKey<AutoCompleteTextFieldState<String>> key = GlobalKey();

  late SimpleAutoCompleteTextField textField;

  List<String> suggestions = [
    "Apple", "Armidillo", "Actual", "Actuary", "America", "Argentina", "Australia", "Antarctica",
    // 更多选项...
  ];

  _FirstPageState() {
    textField = SimpleAutoCompleteTextField(
      key: key,
      decoration: InputDecoration(errorText: "Beans", hintText: "Type something"),
      controller: TextEditingController(),
      suggestions: suggestions,
      textChanged: (text) => currentText = text,
      clearOnSubmit: true,
      textSubmitted: (text) => setState(() {
        if (text != "") {
          added.add(text);
        }
      }),
    );
  }

  bool showWhichErrorText = false;

  [@override](/user/override)
  Widget build(BuildContext context) {
    Column body = Column(children: [
      ListTile(
          title: textField,
          trailing: IconButton(
              icon: Icon(Icons.add),
              onPressed: () {
                textField.triggerSubmitted();
                showWhichErrorText = !showWhichErrorText;
                textField.updateDecoration(
                    decoration: InputDecoration(
                        errorText: showWhichErrorText ? "Beans" : "Tomatoes"));
              })),
    ]);

    body.children.addAll(added.map((item) {
      return ListTile(title: Text(item));
    }));

    return Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
            title: Text('AutoComplete TextField Demo Simple'),
            actions: [
              IconButton(
                  icon: Icon(Icons.edit),
                  onPressed: () => showDialog(
                      builder: (_) {
                        String text = "";

                        return AlertDialog(
                            title: Text("Change Suggestions"),
                            content: TextField(onChanged: (_text) => text = _text),
                            actions: [
                              TextButton(
                                  onPressed: () {
                                    if (text != "") {
                                      suggestions.add(text);
                                      textField.updateSuggestions(suggestions);
                                    }
                                    Navigator.pop(context);
                                  },
                                  child: Text("Add")),
                            ]);
                      },
                      context: context))
            ]),
        body: body);
  }
}

复杂用法页面

class ArbitrarySuggestionType {
  num stars;
  String name, imgURL;

  ArbitrarySuggestionType(this.stars, this.name, this.imgURL);
}

class SecondPage extends StatefulWidget {
  [@override](/user/override)
  State<StatefulWidget> createState() => _SecondPageState();
}

class _SecondPageState extends State<SecondPage> {
  List<ArbitrarySuggestionType> suggestions = [
    ArbitrarySuggestionType(4.7, "Minamishima", "url_to_image"),
    // 更多项...
  ];

  var key = GlobalKey<AutoCompleteTextFieldState<ArbitrarySuggestionType>>();

  late AutoCompleteTextField<ArbitrarySuggestionType> textField;

  var selected = ArbitrarySuggestionType(5.0, "Anchovy", "url_to_image");

  _SecondPageState() {
    textField = AutoCompleteTextField<ArbitrarySuggestionType>(
      decoration: InputDecoration(hintText: "Search Restaurant:", suffixIcon: Icon(Icons.search)),
      itemSubmitted: (item) => setState(() => selected = item),
      key: key,
      suggestions: suggestions,
      itemBuilder: (context, suggestion) => Padding(
          padding: EdgeInsets.all(8.0),
          child: ListTile(
              title: Text(suggestion.name),
              trailing: Text("Stars: ${suggestion.stars}"))),
      itemSorter: (a, b) => a.stars == b.stars ? 0 : a.stars > b.stars ? -1 : 1,
      itemFilter: (suggestion, input) =>
          suggestion.name.toLowerCase().startsWith(input.toLowerCase()),
    );
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(title: Text('AutoComplete TextField Demo Complex')),
      body: Column(children: [
        Padding(padding: EdgeInsets.all(16.0), child: Container(child: textField)),
        Padding(
            padding: EdgeInsets.fromLTRB(0.0, 64.0, 0.0, 0.0),
            child: Card(
                child: Column(children: [
              ListTile(
                  title: Text(selected.name),
                  trailing: Text("Rating: ${selected.stars}/5")),
              Container(
                  child: Image(image: NetworkImage(selected.imgURL)),
                  width: 400.0,
                  height: 300.0)
            ]))),
      ]),
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter应用中使用autocomplete_textfield_ns插件来实现自动补全文本功能的代码示例。这个插件允许你创建一个带有自动补全功能的文本字段,非常适合搜索建议、标签输入等场景。

首先,确保你已经在pubspec.yaml文件中添加了autocomplete_textfield_ns依赖:

dependencies:
  flutter:
    sdk: flutter
  autocomplete_textfield_ns: ^x.y.z  # 请替换为最新版本号

然后,运行flutter pub get来获取依赖。

接下来,你可以在你的Dart文件中使用AutocompleteTextField组件。下面是一个完整的示例,展示了如何实现一个简单的自动补全功能:

import 'package:flutter/material.dart';
import 'package:autocomplete_textfield_ns/autocomplete_textfield.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Autocomplete Textfield Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: AutocompleteDemo(),
    );
  }
}

class AutocompleteDemo extends StatefulWidget {
  @override
  _AutocompleteDemoState createState() => _AutocompleteDemoState();
}

class _AutocompleteDemoState extends State<AutocompleteDemo> {
  final List<String> suggestions = [
    'Apple',
    'Banana',
    'Cherry',
    'Date',
    'Elderberry',
    'Fig',
    'Grape',
    'Honeydew',
    'Kiwi',
    'Lemon'
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Autocomplete Textfield Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: AutocompleteTextField<String>(
          suggestions: suggestions,
          decoration: InputDecoration(
            labelText: 'Search...',
            border: OutlineInputBorder(),
          ),
          itemBuilder: (context, suggestion) {
            return ListTile(
              leading: Icon(Icons.label),
              title: Text(suggestion),
            );
          },
          itemSorter: (a, b) => a.compareTo(b),
          itemFilter: (item, query) {
            return item.toLowerCase().contains(query.toLowerCase());
          },
          onSubmitted: (value) {
            print('Selected: $value');
          },
        ),
      ),
    );
  }
}

代码解释

  1. 依赖导入:首先导入必要的包,包括flutter/material.dartautocomplete_textfield_ns/autocomplete_textfield.dart

  2. 主应用MyApp是一个简单的Flutter应用,包含一个主页面AutocompleteDemo

  3. 自动补全页面

    • 数据准备:在_AutocompleteDemoState中,我们准备了一个字符串列表suggestions作为自动补全的建议项。
    • UI构建:使用AutocompleteTextField组件来构建自动补全文本字段。
      • suggestions:提供建议项的列表。
      • decoration:设置文本字段的装饰,包括标签和边框。
      • itemBuilder:构建每个建议项的UI,这里使用ListTile
      • itemSorter:定义建议项的排序规则,这里按字母顺序排序。
      • itemFilter:定义过滤规则,这里简单地按子字符串匹配过滤。
      • onSubmitted:当用户选择一个建议项时触发的回调,这里简单地打印选中的值。

运行应用

将上述代码保存为一个Dart文件(例如main.dart),然后在你的Flutter项目中运行flutter run即可查看效果。

这个示例展示了如何使用autocomplete_textfield_ns插件创建一个基本的自动补全文本字段。你可以根据需要进一步自定义和扩展这个示例,比如从服务器获取建议项、调整UI风格等。

回到顶部