Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

auto detect link flutter

i have an issue about the text widget not being able to detect that there is a link.

later I will get a text response from the server as shown. the response is in the form of text as well as a link.

the problem is the text widget on flutter can't detect it. How do I make the link in the text detectable and clickable?

I have read and searched about this but could not find it. because most of the link text must be typed by yourself. while my problem the text is automatically there because it is the response from the server

can anyone help me find an answer? Thank you in advance

enter image description here

like image 974
Ewa Saputra Avatar asked Jun 20 '26 01:06

Ewa Saputra


1 Answers

Text widget does not automatically recognise links.

You can, however insert actions to text using the TextSpan widget and url_launcher, somewhat like this:

RichText(
    text: TextSpan(
        children: [
            TextSpan(text: 'some text'),
            TextSpan(
                text: url,
                style: new TextStyle(
                    color: Colors.blue,
                    decoration: TextDecoration.underline
                ),
                recognizer: TapGestureRecognizer()
                ..onTap = () async {
                    if (await canLaunch(url)) {
                      await launch(url);
                    } else {
                      throw 'Could not launch $url';
                    }
                },
            ),
        ]
    ),
)

You can wrap this into a class and make a small LinkText widget for yourself.

What flutter_linkify does is that it automatically detects URLs & email IDs in text and links them. You can also do this using regex. For eg. for identifying url, you could have something like:

 bool _isLink(String input) {
     final matcher = new RegExp(
        r"(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)");
    return matcher.hasMatch(input);
}

You will have to, modify this a bit to get the substring and use that as url in text span!

like image 166
MaddyB Avatar answered Jun 21 '26 15:06

MaddyB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!