我正在尝试制作一个类似于 wats-app 的链接预览功能,它有两个部分,
- 从文本字段检测 URL
- 显示该 URL 的预览
第 2 部分有很多插件可以显示预览,但我一直坚持第 1 部分,即如何检测和解析用户在文本字段中输入的 URL。
还有一个插件可以同时服务这两者吗?
检测字符串/段落中的 URL 并将其转换为 DART 中的链接:
//
String convertStringToLink(String textData) {
//
final urlRegExp = new RegExp(
r"((https?:www\.)|(https?:\/\/)|(www\.))[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9]{1,6}(\/[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)?");
final urlMatches = urlRegExp.allMatches(textData);
List<String> urls = urlMatches.map(
(urlMatch) => textData.substring(urlMatch.start, urlMatch.end))
.toList();
List linksString = [];
urls.forEach((String linkText){
linksString.add(linkText);
});
if (linksString.length > 0) {
linksString.forEach((linkTextData) {
textData = textData.replaceAll(
linkTextData,
'<a href="' +
linkTextData +
'" target="_blank">' +
linkTextData +
'</a>');
});
}
return textData;
}
演示以及如何调用
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));
Output:
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>
它对我有用,肯定会帮助我的朋友:)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)