Flutter富文本装饰插件flutter_decorated_text的使用
Flutter富文本装饰插件 flutter_decorated_text
的使用
DecoratedText
是一个强大的 Flutter 插件,允许你根据预定义的规则对文本的不同部分进行样式设置和交互。它支持多种匹配方式,如特定单词、前缀、标签之间的文本、链接等,并且可以为这些匹配添加不同的样式和交互行为。
主要功能
- 可选文本:通过设置
selectable: true
来启用文本选择。 - 预定义规则:包括匹配特定单词、以特定前缀开头的文本、特定标签之间的文本以及链接(URL)。
- 交互性:每个规则都可以包含一个
onTap
回调函数,返回匹配的文本,允许你实现交互行为,例如点击链接时打开 URL。
使用示例
示例 1:匹配标签之间的文本
DecoratedText(
text: "Like between brackets {this is an example} or html tags <p>this is a paragraph</p>",
rules: [
DecoratorRule.between(
start: "{",
end: "}",
style: TextStyle(color: Colors.blue),
),
DecoratorRule.between(
start: "<p>",
end: "</p>",
style: TextStyle(color: Colors.green),
),
],
);
示例 2:匹配以特定前缀开头的文本
DecoratedText(
text: "Like twitter accounts @gabdsg or hashtags #decoratedtext",
rules: [
DecoratorRule.startsWith(
text: "@",
onTap: (match) {
print(match);
},
style: TextStyle(color: Colors.blue),
),
DecoratorRule.startsWith(
text: "#",
onTap: (match) {
print(match);
},
style: TextStyle(color: Colors.green),
),
],
);
示例 3:匹配特定单词
DecoratedText(
text: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.",
rules: [
DecoratorRule.words(
words: ["lorem ipsum", "industry", "book", "make"],
onTap: (match) {
print(match);
},
style: TextStyle(background: Paint()..color = Colors.yellow),
),
],
);
示例 4:匹配链接(URL)
DecoratedText(
text: "You can match links with https https://pub.dev/ and links without it like google.com",
rules: [
DecoratorRule.url(
onTap: (url) {
print(url);
},
style: TextStyle(color: Colors.blue, decoration: TextDecoration.underline),
),
],
);
示例 5:自定义规则使用正则表达式
DecoratedText(
text: "Match links and add the favicon: https://pub.dev/, https://google.com, stackoverflow.com and talkingpts.org",
rules: [
DecoratorRule(
regExp: RegExp(r'((https?:\/\/)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*))',
caseSensitive: false,
dotAll: true,
multiLine: true,
),
onTap: (url) {
print(url);
},
style: TextStyle(color: Colors.blue),
leadingBuilder: (match) => Container(
width: 16 * 0.8,
height: 16 * 0.8,
margin: const EdgeInsets.only(right: 2, left: 2),
child: CachedNetworkImage(
imageUrl: "${sanitizeUrl(match)}/favicon.ico",
),
),
),
],
);
示例 6:匹配表情符号
DecoratedText(
text: "I love Flutter! 😍",
rules: [
DecoratorRule(
regExp: RegExp(r'(\p{Emoji_Presentation})', unicode: true),
style: const TextStyle(fontSize: 30.0),
onTap: (emoji) {
debugPrint('You tapped on the emoji: $emoji');
},
),
],
);
完整的示例 Demo
以下是一个完整的示例代码,展示了如何在应用中使用 DecoratedText
:
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_decorated_text/flutter_decorated_text.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Decorated text example',
debugShowCheckedModeBanner: false,
theme: ThemeData(primarySwatch: Colors.blue),
home: const ExampleScreen(),
);
}
}
class ExampleScreen extends StatefulWidget {
const ExampleScreen({super.key});
@override
State<ExampleScreen> createState() => _ExampleScreenState();
}
class _ExampleScreenState extends State<ExampleScreen> {
String sanitizeUrl(String url) {
if (!url.startsWith("http://") && !url.startsWith("https://")) {
url = "https://$url";
}
if (url.endsWith(".")) {
url = url.substring(0, url.length - 1);
}
if (url.endsWith("/")) {
url = url.substring(0, url.length - 1);
}
return url;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Decorated text example"),
systemOverlayStyle: SystemUiOverlayStyle.light,
),
body: ListView(
padding: const EdgeInsets.all(40.0),
children: [
Text(
"Match text between tags",
style: Theme.of(context).textTheme.titleLarge,
),
DecoratedText(
selectable: true,
text:
"Like between brackets {this is an example} or html tags <p>this is a paragraph</p> and you can remove the matching characters *between astericks*",
rules: [
DecoratorRule.between(
start: "{",
end: "}",
style: const TextStyle(color: Colors.blue),
),
DecoratorRule.between(
start: "<p>",
end: "</p>",
style: const TextStyle(color: Colors.green),
),
DecoratorRule.between(
start: "*",
end: "*",
style: const TextStyle(fontWeight: FontWeight.bold),
removeMatchingCharacters: true,
),
],
),
const Divider(),
Text(
"Match text starting with",
style: Theme.of(context).textTheme.titleLarge,
),
DecoratedText(
text: "Like twitter accounts @gabdsg or hashtags #decoratedtext",
rules: [
DecoratorRule.startsWith(
text: "@",
onTap: (match) {
debugPrint(match);
},
style: const TextStyle(color: Colors.blue),
),
DecoratorRule.startsWith(
text: "#",
onTap: (match) {
debugPrint(match);
},
style: const TextStyle(color: Colors.green),
),
],
),
const Divider(),
Text(
"Match specific words",
style: Theme.of(context).textTheme.titleLarge,
),
DecoratedText(
text:
"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.",
rules: [
DecoratorRule.words(
words: ["lorem ipsum", "industry", "book", "make"],
onTap: (match) {
debugPrint(match);
},
style: TextStyle(background: Paint()..color = Colors.yellow),
),
],
),
const Divider(),
Text(
"Match links",
style: Theme.of(context).textTheme.titleLarge,
),
DecoratedText(
text:
"You can match links with https https://pub.dev/ and links without it like google.com",
rules: [
DecoratorRule.url(
onTap: (url) {
debugPrint(url);
},
style: const TextStyle(color: Colors.blue, decoration: TextDecoration.underline),
humanize: false,
removeWww: false,
),
],
),
const Divider(),
Text(
"Custom link match",
style: Theme.of(context).textTheme.titleLarge,
),
DecoratedText(
text:
"Match links and add the favicon: https://pub.dev/, https://google.com, stackoverflow.com and talkingpts.org",
rules: [
DecoratorRule(
regExp: RegExp(
r'((https?:\/\/)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*))',
caseSensitive: false,
dotAll: true,
multiLine: true,
),
onTap: (url) {
debugPrint(url);
},
style: const TextStyle(color: Colors.blue),
leadingBuilder: (match) => Container(
width: 16 * 0.8,
height: 16 * 0.8,
margin: const EdgeInsets.only(right: 2, left: 2),
child: CachedNetworkImage(
imageUrl: "${sanitizeUrl(match)}/favicon.ico",
),
),
),
],
),
const Divider(),
Text(
"Match emojis on text",
style: Theme.of(context).textTheme.titleLarge,
),
DecoratedText(
text: "I love Flutter! 😍",
rules: [
DecoratorRule(
regExp: RegExp(r'(\p{Emoji_Presentation})', unicode: true),
style: const TextStyle(fontSize: 30.0),
onTap: (emoji) {
debugPrint('You tapped on the emoji: $emoji');
},
),
],
),
],
),
);
}
}
这个示例展示了如何使用 flutter_decorated_text
包来创建丰富的文本内容,并为其添加样式和交互功能。希望这对你的开发有所帮助!
更多关于Flutter富文本装饰插件flutter_decorated_text的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter富文本装饰插件flutter_decorated_text的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何使用 flutter_decorated_text
插件的示例代码。flutter_decorated_text
是一个用于在 Flutter 中实现富文本装饰的插件。它允许你添加各种装饰,如高亮、下划线、背景颜色等,到文本的不同部分。
首先,你需要在你的 pubspec.yaml
文件中添加 flutter_decorated_text
依赖:
dependencies:
flutter:
sdk: flutter
flutter_decorated_text: ^x.y.z # 请将 x.y.z 替换为最新的版本号
然后运行 flutter pub get
来获取依赖。
接下来是一个完整的示例代码,展示了如何使用 flutter_decorated_text
来创建一个带有装饰的富文本:
import 'package:flutter/material.dart';
import 'package:flutter_decorated_text/flutter_decorated_text.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Decorated Text Example'),
),
body: Center(
child: DecoratedTextExample(),
),
),
);
}
}
class DecoratedTextExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
// 定义一个带有装饰的文本
final decoratedText = DecoratedText(
text: [
DecoratedTextSpan(
text: '这是一个 ',
style: TextStyle(fontSize: 18),
),
DecoratedTextSpan(
text: '高亮',
style: TextStyle(fontSize: 18, color: Colors.blue),
decoration: TextDecoration.highlight,
decorationColor: Colors.yellow,
),
DecoratedTextSpan(
text: ' 的文本,其中 ',
style: TextStyle(fontSize: 18),
),
DecoratedTextSpan(
text: '部分文本',
style: TextStyle(fontSize: 18, color: Colors.red),
decoration: TextDecoration.underline,
backgroundColor: Colors.lightGray.withOpacity(0.3),
),
DecoratedTextSpan(
text: ' 被装饰。',
style: TextStyle(fontSize: 18),
),
],
);
return Padding(
padding: const EdgeInsets.all(16.0),
child: DecoratedTextWidget(decoratedText: decoratedText),
);
}
}
在这个示例中,我们定义了一个 DecoratedText
对象,它包含一个 text
列表,列表中的每个元素都是一个 DecoratedTextSpan
,用于定义文本的各个部分及其装饰。
text
属性用于指定该段文本的内容。style
属性用于指定该段文本的样式,例如字体大小、颜色等。decoration
属性用于指定该段文本的装饰类型,例如高亮、下划线等。decorationColor
属性用于指定高亮装饰的颜色。backgroundColor
属性用于指定文本的背景颜色。
最后,我们使用 DecoratedTextWidget
将 DecoratedText
对象渲染到屏幕上。
希望这个示例能帮助你理解如何使用 flutter_decorated_text
插件来实现富文本装饰。如果你有更具体的需求或问题,请随时告诉我!