dart Flutter 检测网址和显示预览

jljoyd4f  于 2023-01-15  发布在  Flutter
关注(0)|答案(3)|浏览(245)

我试图使一个像wats应用程序链接预览功能,它有两个部分,
1.从文本字段检测URL
1.显示该URL的预览
第2部分有很多插件来显示预览,但我坚持使用第1部分,即如何检测和解析用户在文本字段中输入的URL。
也有一个插件服务两者?

blmhpbnm

blmhpbnm1#

检测字符串/段落中的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));

输出:

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>

它对我起作用了,一定会帮助我的朋友:)

uqxowvwt

uqxowvwt2#

我希望这可以帮助其他人,谈论步骤1:
为了从文本视图中检测URL,我执行了以下操作(考虑到我的用例是聊天消息,其中文本中间可能有一个或多个链接)
首先,有一个函数,给定一个字符串,识别是URL:

bool hasURLs(String text) {
  const pattern =
      r"(https?:\/\/(www.)?|www.)([\w-]+.([\w-]+.)?[\w]+)([\w./?=%-]*)";
  final regExp = RegExp(pattern);
  return regExp.hasMatch(text);
}

然后是显示具有链接或不具有链接的文本消息的逻辑:

final hasUrls = formatter.hasURLs(stringMessage);

在小工具中:

return hasUrls
      ? UrlMessage(
          textContent: messageContents,
          textColor: textColor,
          isMyMessage: isMyMessage,
        )
      : Text(
          messageContents,
          style: TextStyle(color: textColor, fontSize: 13),
        );

对于UrlMessage小部件,代码如下所示:

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(),
      ),
    );
  }
}

关于步骤2,有几个选项可以使用预览,在我们的示例中Any Link Preview可以满足我们的需要

57hvy0tb

57hvy0tb3#

您可以尝试Uri.parse()。请检查链接https://www.geeksforgeeks.org/dart-uris/
使用onChanged函数和控制器从文本字段获取值
https://medium.com/flutter-community/a-deep-dive-into-flutter-textfields-f0e676aaab7a

相关问题