Flutter智能建议插件suggester的使用

Flutter智能建议插件suggester的使用

测试它实时运行!

你可以通过一个在线实例来测试Suggester插件。点击这里访问在线实例

使用

导入

import 'package:suggester/suggester.dart';

选择术语映射

Suggester通过使用术语映射(Term Mapping)将输入和建议项进行分词,并通过前缀搜索找到部分匹配。

例如,一种将输入和建议项分组为字母和数字序列的术语映射:

print(AlphaOrNumeric().map('Armani.Klein3@veda.io', false, false));

输出:

{armani, klein, 3, veda, io}

另一种将输入和建议项分组为大小为3的N-Gram(即三元组)的术语映射:

print(Ngrams(3).map('Armani.Klein3@veda.io', false, false));

输出:

{arm, rma, man, ani, ni., i.k, .kl, kle, lei, ein, in3, n3@, 3@v, @ve, ved, eda, da., a.i, .io}

构建Suggester并加载条目

创建一个小列表作为条目。Suggester可以处理任意数量的条目。

final entries = [
  'Armani.Klein3@veda.io',
  'Tracy@garett.io',
  'Eula@shaniya.name',
  'Reynold.Kunde@leif.net',
  'Reanna@flavio.us',
  'Fidel@nelle.com',
  'Luciano_Pouros@keenan.ca',
  'Curtis_McGlynn@wendell.me',
  'Reese@dante.io',
  'Sallie3@ettie.me',
  'Yolanda@bertram.co.uk',
  'Mariam.Toy@oren.com',
  'Rosalia.Koepp@mellie.name',
  'Rowena.Klein@abdul.us',
  'Jeff@travon.me',
  'Mario_Zulauf@michael.com',
  'Amos@carolina.ca',
  'Lonny_Gleichner@stanton.co.uk',
  'Lula_Bartoletti@makenzie.org',
  'Hardy@marion.ca',
  'Libby_Parker@ursula.biz',
  'banjo.berwen@newell.ca',
  'Genesis@osvaldo.me',
  'Caesar@joana.biz',
  'Cathrine@shayne.info',
  'Bill@dejuan.org',
  'Victor_Crist@dina.ca',
  'Stephany@dillan.io',
  'Emmanuel.Padberg@newell.ca'
];

构建两个示例Suggester对象,每个对象使用不同的术语映射,并加载上述条目列表。

final suggesterAlphaOrNumeric = Suggester(AlphaOrNumeric())
  ..addAll(entries);

final suggesterTrigram = Suggester(Ngrams(3))..addAll(entries);

建议

查找包含搜索词’wen’的所有建议项,注意不同术语映射之间的差异。

print(suggesterAlphaOrNumeric.suggest('wen').map((e) => e.entry.value));

输出:

(Curtis_McGlynn@wendell.me)
print(suggesterTrigram.suggest('wen').map((e) => e.entry.value));

输出:

(Rowena.Klein@abdul.us, banjo.berwen@newell.ca, Curtis_McGlynn@wendell.me)

标记建议搜索词

用户反馈可以通过标记建议中的搜索词来帮助。传递两个自定义函数以应用于标记和未标记的术语。

print(suggesterTrigram.suggest('wen').map((e) => e
    .mapTermsAndNonTerms((term) => '<em>$term</em>', (nonTerm) => nonTerm)
    .join()));

输出:

(Ro<em>wen</em>a.Klein@abdul.us, banjo.ber<em>wen</em>@newell.ca, Curtis_McGlynn@<em>wen</em>dell.me)

使用编辑距离扩展搜索

在搜索时也可以指定编辑距离,允许术语通过汉明编辑距离进行匹配。这会扩展术语映射的范围。使用原始的AlphaOrNumeric示例,最大编辑距离为1:

print(suggesterAlphaOrNumeric
    .suggest('wen', maxEditDistance: 1)
    .map((e) => e.entry.value));

输出:

(Curtis_McGlynn@wendell.me, Genesis@osvaldo.me)

最大编辑距离为2:

for (final suggestion
    in suggesterAlphaOrNumeric.suggest('wen', maxEditDistance: 2)) {
  print(suggestion.entry.value);
}

输出:

Curtis_McGlynn@wendell.me
Genesis@osvaldo.me
Jeff@travon.me
Lonny_Gleichner@stanton.co.uk
Reanna@flavio.us
Reese@dante.io
Reynold.Kunde@leif.net
banjo.berwen@newell.ca
Bill@dejuan.org
Fidel@nelle.com
Yolanda@bertram.co.uk
Emmanuel.Padberg@newell.ca
Luciano_Pouros@keenan.ca
Rosalia.Koepp@mellie.name
Victor_Crist@dina.ca
Armani.Klein3@veda.io

接受建议

一旦选择了建议项,可以通过accept方法记录下来:

final result = suggesterAlphaOrNumeric.suggest('lu');

print(result.map((final suggestion) => suggestion.entry.value));

输出:

(Luciano_Pouros@keenan.ca, Lula_Bartoletti@makenzie.org)

接受最后一个建议项:

result.last.entry.accept();

print(result.map((final suggestion) => suggestion.entry.value));

输出:

(Lula_Bartoletti@makenzie.org, Luciano_Pouros@keenan.ca)

默认情况下,当一个建议被接受时,子评分值会递增,但也可以指定任何整数值,包括时间戳,以便最近使用的建议始终优先。例如:

result.last.entry.accept(subScore: DateTime.now().millisecondsSinceEpoch);

print(result.first.entry);

输出:

{value: Luciano_Pouros@keenan.ca, subScore: 1609579026000}

检查当前条目

遍历所有当前条目:

print(suggesterAlphaOrNumeric.entries);

按子评分顺序遍历所有条目。注意,最后接受的条目排在前面,带有时间戳子评分。

print(suggesterAlphaOrNumeric.entriesBySubScore());

输出:

[{value: Luciano_Pouros@keenan.ca, subScore: 1609569378812},
 {value: Lula_Bartoletti@makenzie.org, subScore: 1},
 {value: Amos@carolina.ca, subScore: 0},
 {value: Armani.Klein3@veda.io, subScore: 0},
 {value: Bill@dejuan.org, subScore: 0},
 {value: Caesar@joana.biz, subScore: 0},
 {value: Cathrine@shayne.info, subScore: 0},
 {value: Curtis_McGlynn@wendell.me, subScore: 0},
 {value: Emmanuel.Padberg@newell.ca, subScore: 0},
 {value: Eula@shaniya.name, subScore: 0},
 ...]

序列化

Suggester是可序列化的,因此建议和批准历史可以轻松存储和重用。

final json = suggesterAlphaOrNumeric.toJson();

final rehydrated = Suggester.fromJson(AlphaOrNumeric(), json);

if (SuggesterEquality().equals(rehydrated, suggesterAlphaOrNumeric)) {
  print('Rehydrated successfully!');
}

输出:

Rehydrated successfully!

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

1 回复

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


当然,关于Flutter智能建议插件suggester的使用,这里提供一个基本的代码示例来展示如何集成和使用该插件(假设suggester是一个假想的插件名称,实际中你可能需要找到具体的第三方插件或者自己实现类似功能)。由于suggester不是官方或广泛认知的插件名称,以下代码是一个模拟的智能建议功能实现,基于常见的搜索建议功能。

首先,你需要确保你的Flutter项目已经设置好,并且添加了必要的依赖(例如,用于处理搜索的网络请求或本地数据)。在这个例子中,我们将模拟一个简单的本地搜索建议功能。

  1. 创建Flutter项目(如果还没有项目的话):
flutter create my_suggester_app
cd my_suggester_app
  1. 添加依赖(这个例子中不需要额外的依赖,但你可能需要http包来从服务器获取数据):

pubspec.yaml文件中添加依赖(如果需要的话):

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.3  # 如果需要从服务器获取数据

然后运行flutter pub get

  1. 创建数据模型(假设我们有一个简单的Suggestion类):
class Suggestion {
  final String text;

  Suggestion({required this.text});
}
  1. 创建建议服务(模拟从本地获取建议):
class SuggestionService {
  final List<Suggestion> suggestions = [
    Suggestion(text: 'Apple'),
    Suggestion(text: 'Banana'),
    Suggestion(text: 'Orange'),
    Suggestion(text: 'Grapes'),
    Suggestion(text: 'Pineapple'),
    // 添加更多建议...
  ];

  List<Suggestion> getSuggestions(String query) {
    return suggestions
        .where((suggestion) =>
            suggestion.text.toLowerCase().contains(query.toLowerCase()))
        .toList();
  }
}
  1. 创建建议列表组件
import 'package:flutter/material.dart';

class SuggestionList extends StatelessWidget {
  final String query;
  final Function(String) onSelected;
  final SuggestionService suggestionService;

  SuggestionList({
    required this.query,
    required this.onSelected,
    required this.suggestionService,
  });

  @override
  Widget build(BuildContext context) {
    final suggestions = suggestionService.getSuggestions(query);

    return ListView.builder(
      itemCount: suggestions.length,
      itemBuilder: (context, index) {
        return ListTile(
          leading: Icon(Icons.search),
          title: Text(suggestions[index].text),
          onTap: () => onSelected(suggestions[index].text),
        );
      },
    );
  }
}
  1. 集成到主应用
import 'package:flutter/material.dart';
import 'suggestion.dart';
import 'suggestion_service.dart';
import 'suggestion_list.dart';

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

class MyApp extends StatelessWidget {
  final SuggestionService suggestionService = SuggestionService();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Suggester Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(suggestionService: suggestionService),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final SuggestionService suggestionService;

  MyHomePage({required this.suggestionService});

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final TextEditingController _controller = TextEditingController();
  String _query = '';

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

  void _onSearchChanged() {
    setState(() {
      _query = _controller.text;
    });
  }

  void _onSuggestionSelected(String selectedText) {
    setState(() {
      _controller.text = selectedText;
      _controller.selection = TextSelection.fromPosition(TextPosition(
        affinity: TextAffinity.downstream,
        offset: selectedText.length,
      ));
    });
    // 可以在这里添加其他逻辑,比如搜索或导航
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Suggester Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            TextField(
              controller: _controller,
              decoration: InputDecoration(
                prefixIcon: Icon(Icons.search),
                hintText: 'Search...',
                suffixIcon: IconButton(
                  icon: Icon(Icons.clear),
                  onPressed: _controller.clear,
                ),
              ),
              onChanged: _onSearchChanged,
            ),
            SizedBox(height: 16),
            if (_query.isNotEmpty)
              SuggestionList(
                query: _query,
                onSelected: _onSuggestionSelected,
                suggestionService: widget.suggestionService,
              ),
          ],
        ),
      ),
    );
  }
}

这个示例展示了如何在Flutter应用中实现一个基本的智能建议功能。它模拟了一个本地搜索建议列表,当用户输入文本时,会动态显示匹配的建议。你可以根据需求扩展这个示例,比如从服务器获取数据、优化UI、添加更多功能等。

请注意,如果你寻找的是特定的第三方插件suggester,你可能需要查找该插件的官方文档来获取具体的集成指南和代码示例。

回到顶部