String text = "This is my website url: https://github.com/ Google search using: www.google.com, Flutter url: http://example.com/method?param=flutter stackoverflow website url is https://www.stackoverflow.com is greatest website and also check this hashed url https://support.google.com/firebase?authuser=0#topic=6399725";
print(convertStringToLink(text));
输出:
This is my website url: <a href="https://github.com/" target="_blank">https://github.com/</a> Google search using: <a href="www.google.com" target="_blank">www.google.com</a>, Flutter url: <a href="http://example.com/method?param=flutter" target="_blank">http://example.com/method?param=flutter</a> stackoverflow website url is <a href="https://www.stackoverflow.com" target="_blank">https://www.stackoverflow.com</a> is greatest website and also check this hashed url <a href="https://support.google.com/firebase?authuser=0#topic=6399725" target="_blank">https://support.google.com/firebase?authuser=0#topic=6399725</a>
class UrlMessage extends StatefulWidget {
const UrlMessage({
Key? key,
required this.textContent,
required this.textColor,
required this.isMyMessage,
}) : super(key: key);
final String textContent;
final Color textColor;
final bool isMyMessage;
@override
State<UrlMessage> createState() => _UrlMessageState();
}
class _UrlMessageState extends State<UrlMessage> {
final formatter = Formatter();
@override
Widget build(BuildContext context) {
final text = widget.textContent;
final textColor = widget.textColor;
final isMyMessage = widget.isMyMessage;
final linkTextStyle = TextStyle(
color: isMyMessage ? Colors.blueGrey : Colors.blue,
fontSize: 13,
fontWeight: FontWeight.bold,
decoration: TextDecoration.underline,
);
return RichText(
// map each word of the message, ask if it is a URL then set it with each
// TextSpan as a link or not. If it's a link use launchUrl from `url_launcher`
// package to open it
text: TextSpan(
children: text.split(' ').map((word) {
// Check for URLs
if (formatter.hasURLs(word)) {
return TextSpan(
text: word,
style: linkTextStyle,
recognizer: TapGestureRecognizer()
..onTap = () {
// Handle link - here we use `url_launcher`
launchUrl(Uri.parse(word));
},
);
} else {
return TextSpan(
text: '$word ',
style: TextStyle(color: textColor, fontSize: 13),
);
}
}).toList(),
),
);
}
}
3条答案
按热度按时间blmhpbnm1#
检测字符串/段落中的URL并将其转换为DART中的链接:
演示和如何致电
输出:
它对我起作用了,一定会帮助我的朋友:)
uqxowvwt2#
我希望这可以帮助其他人,谈论步骤1:
为了从文本视图中检测URL,我执行了以下操作(考虑到我的用例是聊天消息,其中文本中间可能有一个或多个链接)
首先,有一个函数,给定一个字符串,识别是URL:
然后是显示具有链接或不具有链接的文本消息的逻辑:
在小工具中:
对于
UrlMessage
小部件,代码如下所示:关于步骤2,有几个选项可以使用预览,在我们的示例中Any Link Preview可以满足我们的需要
57hvy0tb3#
您可以尝试Uri.parse()。请检查链接https://www.geeksforgeeks.org/dart-uris/
使用onChanged函数和控制器从文本字段获取值
https://medium.com/flutter-community/a-deep-dive-into-flutter-textfields-f0e676aaab7a