Flutter文本搜索高亮插件search_text_highlight_plus的使用

Flutter文本搜索高亮插件search_text_highlight_plus的使用

Search Text Highlight Plus 是一个用于在 Flutter 应用中高亮文本搜索结果的插件。它允许你在文本字段中突出显示搜索词,并提供了多种自定义选项,如高亮颜色和文本样式。

特性

  • 高亮搜索词 在文本字段中。
  • 自定义 高亮颜色和文本样式。
  • 导航 到高亮的文本段落。
  • 支持 大小写敏感和不敏感的搜索。
  • 实时编辑 所选高亮文本。
  • 滚动 到不在可见屏幕上的高亮内容。
  • 支持 多种语言。

安装

在你的 pubspec.yaml 文件中添加以下依赖:

dependencies:
  search_text_highlight_plus: ^0.0.5+3

使用

首先,你需要导入必要的包并创建一个 HighlightTextController 实例。

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

// 创建一个 HighlightTextController 实例
final _highlightTextController = HighlightTextController(
  // 要显示和高亮的文本
  text: englishText.trim(),

  // 控制文本视图的滚动
  scrollController: _scrollController,

  // 当前选择的文本背景色
  selectedTextBackgroundColor: Colors.redAccent,

  // 高亮文本的背景色
  highlightTextBackgroundColor: Colors.yellow,

  // 高亮的选定文本样式
  selectedHighlightedTextStyle: const TextStyle(
    color: Colors.white,
    fontSize: 19,
  ),

  // 非选定的高亮文本样式
  highlightedTextStyle: const TextStyle(
    color: Colors.black,
    fontSize: 19,
  ),
);

自定义

你可以通过传递适当的参数来自定义高亮的颜色和文本样式。

HighlightTextController(
  text: englishText.trim(),
  scrollController: _scrollController,
  selectedTextBackgroundColor: Colors.redAccent,
  highlightTextBackgroundColor: Colors.yellow,
  selectedHighlightedTextStyle: const TextStyle(
    color: Colors.white,
    fontSize: 19,
  ),
  highlightedTextStyle: const TextStyle(
    color: Colors.black,
    fontSize: 19,
  ),
);

示例

这是一个使用 Search Text Highlight Plus 包的基本示例:

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:search_text_highlight_plus/data/highlight_span.dart';
import 'package:search_text_highlight_plus/search_text_highlight_plus.dart';

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HighlightTextEditor(),
    );
  }
}

class HighlightTextEditor extends StatefulWidget {
  const HighlightTextEditor({super.key});

  [@override](/user/override)
  State<HighlightTextEditor> createState() => _HighlightTextEditorState();
}

class _HighlightTextEditorState extends State<HighlightTextEditor> {
  late HighlightTextController _highlightTextController;
  late TextEditingController _searchController;
  late ScrollController _scrollController;
  Timer? _debounceTimer;

  [@override](/user/override)
  void initState() {
    super.initState();
    _searchController = TextEditingController();
    _scrollController = ScrollController();

    _highlightTextController = HighlightTextController(
      text: englishText.trim(),
      scrollController: _scrollController,
      selectedTextBackgroundColor: Colors.redAccent,
      highlightTextBackgroundColor: Colors.yellow,
      selectedHighlightedTextStyle: const TextStyle(
        color: Colors.white,
        fontSize: 19,
      ),
      highlightedTextStyle: const TextStyle(
        color: Colors.black,
        fontSize: 19,
      ),
    );
  }

  [@override](/user/override)
  void dispose() {
    _highlightTextController.dispose();
    _searchController.dispose();
    _scrollController.dispose();
    _debounceTimer?.cancel(); // 释放定时器
    super.dispose();
  }

  // 抖动方法以延迟处理搜索查询
  void _onSearchChanged(String query) {
    if (_debounceTimer?.isActive ?? false) {
      _debounceTimer?.cancel();
    }
    _debounceTimer = Timer(const Duration(milliseconds: 0), () { // 增加抖动时间根据需求
      _highlightTextController.highlightSearchTerm(query);
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Highlight Text Plus')),
      body: SafeArea(
        child: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: TextField(
                controller: _searchController,
                decoration: const InputDecoration(
                  labelText: '输入搜索词',
                  border: OutlineInputBorder(),
                ),
                onChanged: (value) {
                  _onSearchChanged(value); // 使用抖动方法
                },
              ),
            ),
            Expanded(
              child: SingleChildScrollView(
                controller: _highlightTextController.scrollController,
                child: ValueListenableBuilder<List<HighlightSpan>>(
                  valueListenable: _highlightTextController.highlightsNotifier,
                  builder: (context, highlights, child) {
                    return Padding(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 12.0, vertical: 16.0),
                      child: TextField(
                        // readOnly: true,
                        controller: _highlightTextController,
                        maxLines: null,
                        decoration: const InputDecoration(
                          border: OutlineInputBorder(
                            borderSide: BorderSide(color: Colors.grey),
                          ),
                        ),
                        style: const TextStyle(fontSize: 20),
                        onChanged: (value) {
                          _onSearchChanged(_searchController.text.trim());
                        },
                      ),
                    );
                  },
                ),
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          FloatingActionButton(
            onPressed: () {
              _highlightTextController.highlightPrevious();
            },
            child: const Icon(Icons.arrow_upward),
          ),
          const SizedBox(height: 10),
          FloatingActionButton(
            onPressed: () {
              _highlightTextController.highlightNext();
            },
            child: const Icon(Icons.arrow_downward),
          ),
        ],
      ),
    );
  }
}

const englishText = '''
In a small village, there was a small house with a small garden. The small children loved to play with their small toys in the small backyard. Every small detail of their small world brought them immense joy. The small moments they shared were forever cherished in their small hearts. In a small village, there was a small house with a small garden. The small children loved to play with their small toys in the small backyard. Every small detail of their small world brought them immense joy. The small moments they shared were forever cherished in their small hearts. In a small village, there was a small house with a small garden. The small children loved to play with their small toys in the small backyard. Every small detail of their small world brought them immense joy. The small moments they shared were forever cherished in their small hearts. In a small village, there was a small house with a small garden. The small children loved to play with their small toys in the small backyard. Every small detail of their small world brought them immense joy. The small moments they shared were forever cherished in their small hearts.
''';

const arabicText = '''
في قرية صغيرة، كان هناك منزل صغير بحديقة صغيرة. أحب الأطفال الصغار اللعب بألعابهم الصغيرة في الفناء الخلفي الصغير. كل تفصيل صغير في عالمهم الصغير جلب لهم فرحة كبيرة. اللحظات الصغيرة التي شاركوها كانت محبوبة إلى الأبد في قلوبهم الصغيرة. في قرية صغيرة، كان هناك منزل صغير بحديقة صغيرة. أحب الأطفال الصغار اللعب بألعابهم الصغيرة في الفناء الخلفي الصغير. كل تفصيل صغير في عالمهم الصغير جلب لهم فرحة كبيرة. اللحظات الصغيرة التي شاركوها كانت محبوبة إلى الأبد في قلوبهم الصغيرة. في قرية صغيرة، كان هناك منزل صغير بحديقة صغيرة. أحب الأطفال الصغار اللعب بألعابهم الصغيرة في الفناء الخلفي الصغير. كل تفصيل صغير في عالمهم الصغير جلب لهم فرحة كبيرة. اللحظات الصغيرة التي شاركوها كانت محبوبة إلى الأبد في قلوبهم الصغيرة. في قرية صغيرة، كان هناك منزل صغير بحديقة صغيرة. أحب الأطفال الصغار اللعب بألعابهم الصغيرة في الفناء الخلفي الصغير. كل تفصيل صغير في عالمهم الصغير جلب لهم فرحة كبيرة. اللحظات الصغيرة التي شاركوها كانت محبوبة إلى الأبد في قلوبهم الصغيرة.
''';

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

1 回复

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


当然,下面是一个关于如何在Flutter应用中使用search_text_highlight_plus插件来实现文本搜索高亮的代码示例。这个插件允许你在搜索到的文本中高亮显示匹配的关键词。

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

dependencies:
  flutter:
    sdk: flutter
  search_text_highlight_plus: ^0.2.0  # 请检查最新版本号

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

以下是一个完整的示例代码,展示了如何使用search_text_highlight_plus插件:

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

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

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

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  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 = "";

  @override
  Widget build(BuildContext context) {
    List<HighlightResult> highlightedResults = computeHighlightResults(
      textToSearch,
      searchQuery,
      textStyle: TextStyle(color: Colors.black, fontSize: 16),
      highlightStyle: TextStyle(backgroundColor: Colors.yellow, fontSize: 16),
    );

    return Scaffold(
      appBar: AppBar(
        title: Text("Search Text Highlight Demo"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextField(
              decoration: InputDecoration(
                labelText: "Search Query",
                border: OutlineInputBorder(),
              ),
              onChanged: (value) {
                setState(() {
                  searchQuery = value;
                });
              },
            ),
            SizedBox(height: 16),
            Expanded(
              child: HighlightText(
                highlightedResults,
              ),
            ),
          ],
        ),
      ),
    );
  }

  List<HighlightResult> computeHighlightResults(
    String text,
    String query, {
    TextStyle textStyle,
    TextStyle highlightStyle,
  }) {
    if (query.isEmpty) {
      return [
        HighlightResult(
          textStyle: textStyle,
          children: [TextSpan(text: text)],
        ),
      ];
    }

    List<String> queryWords = query.split(" ");
    return highlight(text, queryWords, textStyle: textStyle, highlightStyle: highlightStyle);
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,其中包含一个TextField用于输入搜索查询,以及一个HighlightText小部件用于显示高亮结果。

computeHighlightResults函数负责计算高亮结果。如果查询为空,它会返回一个包含整个文本的HighlightResult。如果查询不为空,它会将查询拆分成单词列表,并调用highlight函数来生成高亮结果。

HighlightText小部件用于显示高亮结果。由于search_text_highlight_plus插件的HighlightText构造函数接受一个List<HighlightResult>,因此我们直接传递计算得到的结果。

请确保你查看search_text_highlight_plus的文档和最新版本,因为API可能会有所变化。上述代码基于插件的当前实现,但在实际应用中,你可能需要根据最新的插件版本和API进行调整。

回到顶部