Flutter文本高亮插件highlightable_text的使用

Flutter文本高亮插件highlightable_text的使用

README.md를 더 상세하게 작성해드리겠습니다.

Highlightable Text

텍스트 하이라이트 기능과 메모 기능을 제공하는 Flutter 위젯입니다. 긴 텍스트에서 중요한 부분을 하이라이트하고 메모를 추가할 수 있습니다.

主要功能

  • 长按以实现文本高亮
  • 支持多种高亮颜色
  • 可以为高亮文本添加备注
  • 自定义备注对话框支持
  • 自定义备注指示器支持
  • 支持滚动
  • 初始高亮列表支持

安装

pubspec.yaml 文件中添加以下内容:

dependencies:
  highlightable_text: ^0.0.1

基本用法

最基础的使用示例:

HighlightableText(
  text: "测试高亮功能的长文本...",
  onSaveNote: (highlight, note) {
    print('高亮的文本: ${highlight.content}');
    print('备注: $note');
  },
)

高级用法

1. 高亮状态管理

class MyWidget extends StatefulWidget {
  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  final List<Highlight> _highlights = [];
  Color _currentColor = Colors.yellow.withOpacity(0.3);

  @override
  Widget build(BuildContext context) {
    return HighlightableText(
      text: "长文本内容...",
      initialHighlights: _highlights,
      selectedColor: _currentColor,
      onHighlight: (content, start, end) {
        print('新高亮: $content');
      },
      onSaveNote: (highlight, note) {
        setState(() {
          final index = _highlights.indexWhere(
            (h) => h.startOffset == highlight.startOffset && h.endOffset == highlight.endOffset,
          );
          if (index != -1) {
            _highlights[index] = highlight.copyWith(note: note);
          }
        });
      },
    );
  }
}

2. 自定义备注对话框

带标签功能的自定义备注对话框示例:

HighlightableText(
  text: "文本内容...",
  noteBuilder: (context, highlight, onSave) {
    return CustomNoteDialog(
      highlight: highlight,
      onSave: onSave,
    );
  },
)

// 自定义对话框实现
class CustomNoteDialog extends StatefulWidget {
  final Highlight highlight;
  final OnSaveNoteCallback onSave;

  const CustomNoteDialog({
    required this.highlight,
    required this.onSave,
  });

  @override
  State<CustomNoteDialog> createState() => _CustomNoteDialogState();
}

class _CustomNoteDialogState extends State<CustomNoteDialog> {
  late TextEditingController _noteController;

  @override
  void initState() {
    super.initState();
    _noteController = TextEditingController(text: widget.highlight.note);
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('备注'),
      content: TextField(
        controller: _noteController,
        maxLines: 3,
        decoration: const InputDecoration(
          hintText: '请输入备注',
          border: OutlineInputBorder(),
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('取消'),
        ),
        TextButton(
          onPressed: () => widget.onSave(
            widget.highlight,
            _noteController.text,
          ),
          child: const Text('保存'),
        ),
      ],
    );
  }
}

3. 自定义备注指示器

HighlightableText(
  text: "文本内容...",
  noteIndicatorBuilder: (highlight) => Padding(
    padding: const EdgeInsets.only(left: 4),
    child: Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(
          Icons.note,
          size: 16,
          color: highlight.note?.isNotEmpty == true
              ? Colors.blue
              : Colors.grey[400],
        ),
        if (highlight.note?.isNotEmpty == true) ...[
          const SizedBox(width: 4),
          Container(
            padding: const EdgeInsets.symmetric(
              horizontal: 4,
              vertical: 2,
            ),
            decoration: BoxDecoration(
              color: Colors.grey[200],
              borderRadius: BorderRadius.circular(4),
            ),
            child: Text(
              '备注',
              style: TextStyle(fontSize: 10),
            ),
          ),
        ],
      ],
    ),
  ),
)

属性说明

必需属性

  • text: 要显示的文本内容

可选属性

  • textStyle: 默认文本样式
  • highlightColors: 可用的高亮颜色列表
  • initialHighlights: 初始高亮列表
  • selectedColor: 当前选择的高亮颜色
  • selectionOpacity: 选择时的高亮不透明度
  • scrollController: 滚动控制器

回调

  • onHighlight: 新建高亮时调用
  • onHighlightTap: 点击高亮时调用
  • onSaveNote: 保存备注时调用

自定义

  • noteBuilder: 自定义备注对话框构建器
  • noteIndicatorBuilder: 自定义备注指示器构建器

许可证

MIT License - 详细内容请参阅 LICENSE 文件。

贡献

如果发现 bug 或有新的功能建议,请在 GitHub Issues 中创建问题。

FAQ

Q: 如何动态更改高亮颜色?

Color _currentColor = Colors.yellow.withOpacity(0.3);

HighlightableText(
  text: "文本内容...",
  selectedColor: _currentColor,
)

Q: 如何滚动到高亮文本的位置?

final scrollController = ScrollController();

HighlightableText(
  text: "文本内容...",
  scrollController: scrollController,
)

// 移动滚动位置
scrollController.animateTo(
  position,
  duration: Duration(milliseconds: 300),
  curve: Curves.easeInOut,
);

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

1 回复

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


highlightable_text 是一个用于在 Flutter 应用中实现文本高亮的插件。它允许你根据特定的条件或正则表达式来高亮显示文本中的某些部分。以下是如何使用 highlightable_text 插件的基本步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  highlightable_text: ^1.0.0  # 请使用最新版本

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

2. 导入包

在你的 Dart 文件中导入 highlightable_text 包:

import 'package:highlightable_text/highlightable_text.dart';

3. 使用 HighlightableText 组件

HighlightableText 组件允许你定义高亮规则,并将其应用到文本中。以下是一个简单的示例:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Highlightable Text Example'),
        ),
        body: Center(
          child: HighlightableText(
            text: 'This is a sample text with some keywords like Flutter and Dart.',
            highlights: [
              Highlight(
                term: 'Flutter',
                style: TextStyle(
                  color: Colors.blue,
                  fontWeight: FontWeight.bold,
                ),
              ),
              Highlight(
                term: 'Dart',
                style: TextStyle(
                  color: Colors.red,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
            style: TextStyle(
              fontSize: 18,
              color: Colors.black,
            ),
          ),
        ),
      ),
    );
  }
}

4. 解释代码

  • text: 这是你想要显示的文本。
  • highlights: 这是一个 List<Highlight>,每个 Highlight 对象定义了要匹配的文本(term)以及匹配后的样式(style)。
  • style: 这是整个文本的默认样式。

5. 自定义高亮规则

你可以通过 Highlight 类的 term 属性来指定要匹配的文本,并通过 style 属性来定义匹配后的文本样式。你还可以使用正则表达式来匹配更复杂的模式。

例如,如果你想高亮所有以 F 开头的单词,可以使用正则表达式:

highlights: [
  Highlight(
    term: r'\bF\w+',
    style: TextStyle(
      color: Colors.green,
      fontWeight: FontWeight.bold,
    ),
    isRegex: true,  // 设置为 true 以使用正则表达式
  ),
],
回到顶部