Flutter智能建议输入插件suggestion_input_field的使用

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

Flutter智能建议输入插件suggestion_input_field的使用

SuggestionTextField

SuggestionTextField 是一个Flutter插件,它提供了一个带有自动建议功能的文本输入框。这个插件在用户需要从预定义列表中选择输入数据的场景下非常有用。

安装

要使用 SuggestionTextField,请在您的 pubspec.yaml 文件中添加以下依赖项:

dependencies:  
  suggestion_text_field: ^1.0.5

使用方法

导入插件并在您的Flutter应用中使用 SuggestionTextField 小部件。以下是一个完整的示例代码:

import 'dart:async';
import 'dart:math';

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

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Suggestion Input Field',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Suggestion Input Field'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  Customer? selectedCustomer;

  // 模拟从异步任务或非异步任务中获取客户数据
  FutureOr<List<Customer>> fetchCustomerData(String filterText) async {
    final List<Customer> customers = List.generate(20, (index) {
      final random = Random();
      final id = 'C${random.nextInt(10000)}';
      final name = 'Customer ${index + 1}';
      final mobile = '555-555-${random.nextInt(10000)}';
      return Customer(id: id, name: name, mobile: mobile);
    });

    // 返回过滤后的数据
    return customers
        .where((element) =>
            element.name.toLowerCase().contains(filterText.toLowerCase()))
        .toList();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: SizedBox(
          width: 300,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              TextButton(
                onPressed: () => setState(() {
                  selectedCustomer = null;
                }),
                child: const Text('清除客户'),
              ),
              TextButton(
                onPressed: () => setState(() {
                  selectedCustomer = Customer(
                      id: "100",
                      name: "外部客户",
                      mobile: "555-555-5555");
                }),
                child: const Text('设置外部客户'),
              ),
              const SizedBox(height: 100),
              SuggestionTextField<Customer>(
                value: selectedCustomer,
                suggestionFetch: (textEditingValue) =>
                    fetchCustomerData(textEditingValue.text),
                textFieldContent: TextFieldContent(
                  decoration: const InputDecoration(
                    labelText: '选择客户',
                  ),
                ),
                displayStringForOption: (option) => option.name,
                onSelected: (option) {
                  setState(() {
                    selectedCustomer = option;
                  });
                },
                onClose: () {
                  setState(() {
                    selectedCustomer = null;
                  });
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class Customer {
  final String id;
  final String name;
  final String mobile;

  Customer({required this.id, required this.name, required this.mobile});
}

更多关于Flutter智能建议输入插件suggestion_input_field的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter智能建议输入插件suggestion_input_field的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter项目中使用suggestion_input_field插件的代码示例。这个插件可以帮助你在输入字段中显示智能建议。

首先,你需要在pubspec.yaml文件中添加suggestion_input_field依赖:

dependencies:
  flutter:
    sdk: flutter
  suggestion_input_field: ^最新版本号  # 请替换为当前最新版本号

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

接下来是一个简单的示例代码,展示如何使用suggestion_input_field插件:

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

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

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

class SuggestionInputFieldScreen extends StatefulWidget {
  @override
  _SuggestionInputFieldScreenState createState() => _SuggestionInputFieldScreenState();
}

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

  final TextEditingController controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Suggestion Input Field Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: SuggestionInputField(
          controller: controller,
          suggestions: suggestions,
          suggestionItemBuilder: (context, suggestion) {
            return ListTile(
              leading: Icon(Icons.text_fields),
              title: Text(suggestion),
            );
          },
          onSuggestionSelected: (suggestion) {
            controller.value = controller.value.copyWith(
              text: suggestion,
              selection: TextSelection.fromPosition(TextPosition(offset: suggestion.length)),
            );
          },
          onTextChanged: (text) {
            // 处理文本变化,如果需要的话
          },
          decoration: InputDecoration(
            labelText: 'Enter text',
            border: OutlineInputBorder(),
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
}

在这个示例中:

  1. SuggestionInputField是核心组件,它接受多个参数:

    • controller:一个TextEditingController,用于管理输入字段的状态。
    • suggestions:一个字符串列表,包含可能的建议。
    • suggestionItemBuilder:一个函数,用于构建每个建议项的UI。
    • onSuggestionSelected:一个回调函数,当用户选择一个建议时调用。
    • onTextChanged:一个回调函数,当输入文本发生变化时调用(可选)。
    • decoration:一个InputDecoration,用于自定义输入字段的外观。
  2. 我们在dispose方法中调用controller.dispose()来释放资源。

这个示例展示了如何使用suggestion_input_field插件来创建一个带有智能建议的输入字段。你可以根据自己的需求进一步自定义和扩展这个示例。

回到顶部