Flutter文本高亮插件highlights_plugin的使用
Flutter文本高亮插件highlights_plugin的使用
Dart实现的highlights KMP引擎: https://github.com/SnipMeDev/Highlights
安装
在pubspec.yaml
文件中添加以下依赖:
flutter pub add highlights_plugin
使用
首先,初始化HighlightsPlugin
实例并获取语言列表和主题列表。然后,使用PhraseLocation
对象来指定要高亮的文本部分,并调用getHighlights
方法来获取高亮结果。
final plugin = HighlightsPlugin(debug: true);
// 获取支持的语言列表
final languages = await plugin.getLanguages();
// 获取内置的主题列表
final themes = await plugin.getThemes();
// 高亮 "Hello" 关键字
final emphasis = PhraseLocation(start: 3, length: 8);
// 获取高亮后的结果
final result = await plugin.getHighlights(
'// Hello, World!',
languages.first,
themes.first,
[emphasis],
);
示例代码
以下是一个完整的示例,展示了如何在Flutter应用中使用highlights_plugin
插件进行文本高亮。
import 'package:flutter/material.dart';
import 'package:highlights_plugin/highlights_plugin.dart';
import 'package:highlights_plugin/model/phrase_location.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final _highlightsPlugin = HighlightsPlugin(debug: true);
String? _code;
String? _language;
String? _theme;
List<String> _highlights = [];
final List<PhraseLocation> _emphasis = [];
// 更新暗模式
Future<void> _updateDarkMode(bool isDark) async {
_highlightsPlugin.setDarkMode(isDark);
_updateHighlights(_code ?? '');
}
// 更新语言
void _updateLanguage(String language) {
setState(() {
_language = language;
});
_updateHighlights(_code ?? '');
}
// 更新主题
void _updateTheme(String theme) {
setState(() {
_theme = theme;
});
_updateHighlights(_code ?? '');
}
// 更新高亮结果
Future<void> _updateHighlights(String code) async {
_code = code;
_highlightsPlugin
.getHighlights(
_code ?? '',
_language,
_theme,
_emphasis,
)
.then((value) {
setState(() {
value.sort((a, b) => a.location.start.compareTo(b.location.start));
_highlights = value.map((highlight) => highlight.toString()).toList();
});
});
}
// 添加高亮位置
void _addEmphasis(PhraseLocation location) {
_emphasis.add(location);
_updateHighlights(_code ?? '');
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('高亮插件示例'),
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: _EditableTextField(
onChange: (code) => _updateHighlights(code),
onBold: (location) {
_addEmphasis(location);
},
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
_highlights.join("\n"),
textAlign: TextAlign.start,
),
),
)
],
),
bottomNavigationBar: Padding(
padding: const EdgeInsets.all(16),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_ThemeSwitchRow(
onChange: (isDark) => _updateDarkMode(isDark),
),
FutureDropdown(
selected: _language,
future: _highlightsPlugin.getLanguages(),
onChanged: _updateLanguage,
),
const SizedBox(height: 16),
FutureDropdown(
selected: _theme,
future: _highlightsPlugin.getThemes(),
onChanged: _updateTheme,
),
],
),
),
),
);
}
}
// 可编辑文本框组件
class _EditableTextField extends StatelessWidget {
const _EditableTextField({
required this.onChange,
required this.onBold,
});
final void Function(String) onChange;
final void Function(PhraseLocation) onBold;
@override
Widget build(BuildContext context) {
return TextField(
onChanged: onChange,
maxLines: 20,
keyboardType: TextInputType.multiline,
decoration: const InputDecoration(
border: OutlineInputBorder(),
),
contextMenuBuilder: (context, state) {
final TextEditingValue value = state.textEditingValue;
final List<ContextMenuButtonItem> buttonItems = state.contextMenuButtonItems;
buttonItems.insert(
0,
ContextMenuButtonItem(
label: '加粗',
onPressed: () {
ContextMenuController.removeAny();
final range = value.selection;
onBold(PhraseLocation(start: range.start, end: range.end));
},
),
);
return AdaptiveTextSelectionToolbar.buttonItems(
anchors: state.contextMenuAnchors,
buttonItems: buttonItems,
);
},
);
}
}
// 主题切换行组件
class _ThemeSwitchRow extends StatefulWidget {
const _ThemeSwitchRow({required this.onChange});
final void Function(bool) onChange;
@override
State<_ThemeSwitchRow> createState() => _ThemeSwitchRowState();
}
class _ThemeSwitchRowState extends State<_ThemeSwitchRow> {
var isDark = false;
@override
Widget build(BuildContext context) {
void onChanged(bool value) {
widget.onChange(value);
setState(() {
isDark = value;
});
}
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
const Icon(Icons.brightness_4),
Switch(
value: isDark,
onChanged: (isDark) => onChanged(isDark),
),
const Icon(Icons.brightness_2),
],
);
}
}
// 异步下拉选择框组件
class FutureDropdown<T> extends StatelessWidget {
const FutureDropdown({
required this.selected,
required this.future,
required this.onChanged,
super.key,
});
final T? selected;
final Future<List<T>> future;
final Function(T) onChanged;
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: future,
builder: (context, snapshot) {
final isLoaded = snapshot.connectionState == ConnectionState.done;
final data = snapshot.data;
final items = data?.map<DropdownMenuItem<String>>(
(value) => DropdownMenuItem(
value: value as String,
child: Text(value),
),
);
if (!isLoaded) {
return const CircularProgressIndicator();
} else {
return DropdownButton(
hint: const Text("选择"),
value: selected,
items: items?.toList(),
onChanged: (value) => onChanged(value as T),
);
}
},
);
}
}
功能
- 支持17种编程语言(如Kotlin、Dart、Swift等)
- 支持浅色/深色模式
- 提供6种内置主题
- 支持关键词加粗
- 结果缓存及增量更新支持
支持平台
- Android: ✅
- iOS: ✅
- macOS: 🔴 (尚未支持)
- Linux: 🔴 (尚未支持)
- Windows: 🔴 (尚未支持)
- Web: 🔴 (尚未支持)
许可证 🖋️
Copyright 2024 Tomasz Kądziołka.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
更多关于Flutter文本高亮插件highlights_plugin的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter文本高亮插件highlights_plugin的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
highlights_plugin
是一个用于在 Flutter 应用中实现文本高亮的插件。它允许你在文本中高亮显示特定的单词或短语,并且可以自定义高亮的样式。
1. 添加依赖
首先,你需要在 pubspec.yaml
文件中添加 highlights_plugin
插件的依赖:
dependencies:
flutter:
sdk: flutter
highlights_plugin: ^最新版本
然后运行 flutter pub get
来安装依赖。
2. 使用 HighlightsPlugin
highlights_plugin
提供了一个 Highlights
小部件,你可以用它来包裹你的文本,并指定需要高亮的单词或短语。
import 'package:flutter/material.dart';
import 'package:highlights_plugin/highlights_plugin.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Text Highlight Example'),
),
body: Center(
child: Highlights(
text: 'This is a sample text to demonstrate how to highlight words in Flutter.',
highlights: ['sample', 'highlight', 'Flutter'],
highlightStyle: TextStyle(
backgroundColor: Colors.yellow,
color: Colors.black,
fontWeight: FontWeight.bold,
),
textStyle: TextStyle(
fontSize: 16.0,
color: Colors.black,
),
),
),
),
);
}
}
3. 参数说明
text
: 要显示的文本。highlights
: 需要高亮的单词或短语列表。highlightStyle
: 高亮文本的样式。textStyle
: 普通文本的样式。
4. 自定义高亮样式
你可以通过 highlightStyle
参数来自定义高亮文本的样式,例如背景颜色、字体颜色、字体粗细等。
highlightStyle: TextStyle(
backgroundColor: Colors.yellow,
color: Colors.black,
fontWeight: FontWeight.bold,
),
5. 处理点击事件
highlights_plugin
还支持处理高亮文本的点击事件。你可以通过 onHighlightTap
回调来处理用户点击高亮文本时的操作。
Highlights(
text: 'This is a sample text to demonstrate how to highlight words in Flutter.',
highlights: ['sample', 'highlight', 'Flutter'],
highlightStyle: TextStyle(
backgroundColor: Colors.yellow,
color: Colors.black,
fontWeight: FontWeight.bold,
),
textStyle: TextStyle(
fontSize: 16.0,
color: Colors.black,
),
onHighlightTap: (String highlightedText) {
print('You tapped on: $highlightedText');
},
),
6. 其他功能
highlights_plugin
还支持其他一些功能,例如:
- 区分大小写: 通过
caseSensitive
参数来控制是否区分大小写。 - 正则表达式: 通过
useRegex
参数来使用正则表达式进行匹配。
Highlights(
text: 'This is a sample text to demonstrate how to highlight words in Flutter.',
highlights: ['sample', 'highlight', 'Flutter'],
caseSensitive: false,
useRegex: false,
highlightStyle: TextStyle(
backgroundColor: Colors.yellow,
color: Colors.black,
fontWeight: FontWeight.bold,
),
textStyle: TextStyle(
fontSize: 16.0,
color: Colors.black,
),
),