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

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

这是一个简单的继承小部件,用于在搜索结果中高亮文本,支持自定义高亮颜色和高亮样式。

功能

  • 在搜索结果中高亮文本,并支持自定义高亮颜色和高亮样式。
  • 不直接解析搜索文本即可高亮文本。
  • 支持将搜索文本作为正则表达式解析。

使用方法

// 使用 SearchTextInheritedWidget 包装需要高亮的文本
SearchTextInheritedWidget(
  searchText: '搜索文本',
  child: SearchHighlightText('需要高亮的文本'),
),

// 或者使用正则表达式
SearchTextInheritedWidget(
  // 可以使用任何正则表达式,例如 RegExp('[1-9]'), RegExp('搜索文本带正则', caseSensitive: false) 等
  searchRegExp: RegExp('搜索文本带正则'),
  child: SearchHighlightText('需要高亮的文本'),
),

也可以直接使用 SearchHighlightText,但需要提供 searchTextsearchRegExp 参数。

SearchHighlightText(
  '需要高亮的文本',
  searchText: '搜索文本',
),

示例

完整的示例可以在 仓库 中查看。

搜索视图

// search_view.dart

class SearchView extends ConsumerWidget {
  const SearchView({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context, WidgetRef ref) {
    var controller = ref.watch(searchController);

    return GestureDetector(
      onTap: () {
        FocusManager.instance.primaryFocus?.unfocus(); // 移除焦点
      },
      child: Scaffold(
        backgroundColor: Colors.grey[100],
        appBar: AppBar(
          title: const Text('搜索电影示例'),
        ),
        body: Column(
          children: [
            const SizedBox(
              height: 10,
            ),
            SearchField(
              controller: controller,
            ),
            Expanded(
              child: controller.isLoading
                  ? const Center(
                      child: CircularProgressIndicator(), // 加载指示器
                    )
                  : SearchTextInheritedWidget(
                      searchText: controller.searchText, // 传递搜索文本到 widget 树,供 SearchHighlightText 使用
                      child: ListMoviesWidget(
                        listMovies: controller.movies,
                      ),
                    ),
            ),
          ],
        ),
      ),
    );
  }
}

电影卡片

// movie_card.dart

class MovieCard extends StatelessWidget {
  const MovieCard({Key? key, required this.movie}) : super(key: key);

  final MovieModel movie;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Card(
      child: ListTile(
        title: SearchHighlightText( // 使用 SearchHighlightText 小部件高亮搜索文本(如果有)
          movie.title,
        ),
        subtitle: Text(movie.year),
        leading: SizedBox(
          width: 100,
          child: Image.network(
            movie.posterUrl,
            fit: BoxFit.cover,
            errorBuilder: (context, error, stackTrace) {
              return const Icon(Icons.error); // 错误占位符
            },
          ),
        ),
      ),
    );
  }
}

完整示例代码

// main.dart

import 'package:example/search/views/search_view.dart';
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return ProviderScope(
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        title: '搜索高亮文本示例',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: const SearchView(),
      ),
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter项目中使用search_highlight_text插件来实现文本高亮搜索的示例代码。这个插件可以帮助你在一段文本中高亮显示匹配的搜索词。

首先,你需要在你的pubspec.yaml文件中添加这个插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  search_highlight_text: ^1.0.12  # 请确保版本号是最新的

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

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

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter 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 for building natively compiled applications for mobile, web, and desktop from a single codebase.";
  String searchQuery = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Text Highlight Search Demo"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: <Widget>[
            TextField(
              decoration: InputDecoration(labelText: 'Search Query'),
              onChanged: (value) {
                setState(() {
                  searchQuery = value;
                });
              },
            ),
            SizedBox(height: 16),
            Expanded(
              child: HighlightText(
                textToSearch,
                searchQuery,
                textStyle: TextStyle(color: Colors.black),
                highlightTextStyle: TextStyle(
                  color: Colors.red,
                  backgroundColor: Colors.yellow.withOpacity(0.5),
                  fontWeight: FontWeight.bold,
                ),
                textAlign: TextAlign.justify,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

代码解释

  1. 依赖添加

    • pubspec.yaml中添加search_highlight_text依赖。
  2. 应用结构

    • MyApp:根应用组件。
    • MyHomePage:包含搜索功能的主页面。
  3. 搜索功能

    • TextField:用于输入搜索查询。
    • HighlightText:用于显示高亮文本。
  4. 高亮文本

    • textToSearch:要搜索的原始文本。
    • searchQuery:用户输入的搜索查询。
    • HighlightText组件接受以下参数:
      • textToSearch:原始文本。
      • searchQuery:要搜索的查询字符串。
      • textStyle:原始文本的样式。
      • highlightTextStyle:高亮文本的样式。
      • textAlign:文本对齐方式。

这个示例展示了如何在Flutter应用中实现文本高亮搜索功能。用户输入查询后,匹配的文本部分会被高亮显示。你可以根据需要调整样式和布局。

回到顶部