Flutter文本搜索插件teno_textsearch的使用

Flutter 文本搜索插件 teno_textsearch 的使用

特性

  • 索引 JSON 文档。
  • 导出/导入索引。

开始使用

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

dependencies:
  teno_textsearch: ^最新版本号

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

使用方法

以下是一个简单的示例,展示如何使用 teno_textsearch 插件来索引和搜索文档。

示例代码
import 'package:flutter/material.dart';
import 'package:teno_textsearch/teno_textsearch.dart';

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("TenoTextSearch Demo")),
        body: SearchPage(),
      ),
    );
  }
}

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

class _SearchPageState extends State<SearchPage> {
  final engine = TenoTextSearch(indexKey: 'id', indexFields: ['title']);
  
  [@override](/user/override)
  void initState() {
    super.initState();
    // 索引文档
    engine.index({
      'id': 'doc1',
      'title': 'First document',
      'description': 'no description'
    });
    engine.index({'id': 'doc2', 'title': 'Second document'});
  }

  String searchResult = '';

  void performSearch(String query) {
    setState(() {
      searchResult = engine.search(query).toString();
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Column(
        children: [
          TextField(
            decoration: InputDecoration(hintText: "输入搜索词"),
            onChanged: (value) => performSearch(value),
          ),
          SizedBox(height: 20),
          Text(
            "搜索结果: $searchResult",
            style: TextStyle(fontSize: 18),
          ),
        ],
      ),
    );
  }
}

更多关于Flutter文本搜索插件teno_textsearch的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

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


当然,以下是如何在Flutter应用中使用teno_textsearch插件的一个示例代码案例。这个插件主要用于在文本中执行高效的搜索操作,并高亮显示匹配的结果。

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

dependencies:
  flutter:
    sdk: flutter
  teno_textsearch: ^最新版本号  # 替换为实际的最新版本号

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

接下来,是一个示例代码,展示了如何使用teno_textsearch插件:

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

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

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

class TextSearchScreen extends StatefulWidget {
  @override
  _TextSearchScreenState createState() => _TextSearchScreenState();
}

class _TextSearchScreenState extends State<TextSearchScreen> {
  final String textToSearch =
      "Flutter is an open-source UI software development kit created by Google. It is used for developing applications for Android, iOS, Linux, Mac, Windows, and the web from a single codebase.";
  String searchQuery = "";
  TextSearchController _textSearchController;

  @override
  void initState() {
    super.initState();
    _textSearchController = TextSearchController(textToSearch);
  }

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

  void _onSearchChanged(String value) {
    setState(() {
      searchQuery = value;
      _textSearchController.search(searchQuery);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Text Search Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextField(
              decoration: InputDecoration(
                labelText: 'Search',
                suffixIcon: IconButton(
                  icon: Icon(Icons.clear),
                  onPressed: () {
                    setState(() {
                      searchQuery = "";
                      _textSearchController.reset();
                    });
                  },
                ),
              ),
              onChanged: _onSearchChanged,
            ),
            SizedBox(height: 16),
            Expanded(
              child: Text.rich(
                TextSpan(
                  children: _textSearchController.matches.map((match) {
                    final TextStyle matchStyle = TextStyle(
                      backgroundColor: Colors.yellow.withOpacity(0.5),
                    );
                    final TextStyle normalStyle = TextStyle(color: Colors.black);
                    return TextSpan(
                      text: textToSearch.substring(0, match.start),
                      style: normalStyle,
                      children: <TextSpan>[
                        TextSpan(
                          text: textToSearch.substring(match.start, match.end),
                          style: matchStyle,
                        ),
                        if (match.end < textToSearch.length)
                          TextSpan(
                            text: textToSearch.substring(match.end),
                            style: normalStyle,
                          ),
                      ],
                    );
                  }).toList(),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

解释

  1. 依赖添加:在pubspec.yaml中添加teno_textsearch依赖。
  2. UI结构
    • 使用TextField作为搜索框,用户可以在其中输入搜索查询。
    • 当搜索查询变化时,调用_onSearchChanged方法。
  3. 搜索逻辑
    • 初始化TextSearchController并传入要搜索的文本。
    • _onSearchChanged方法中,根据用户的输入调用_textSearchController.search(searchQuery)进行搜索。
  4. 显示结果
    • 使用Text.richTextSpan来构建高亮显示的文本。
    • 遍历搜索结果中的匹配项,并根据匹配的开始和结束位置来分割和着色文本。

这样,你就可以在Flutter应用中实现文本搜索并高亮显示匹配结果的功能了。

回到顶部