Flutter URL Launcher for HTML content is not working

Viewed 3082

I am developing an app using Flutter. Now I need to render the HTML content in my application that includes anchor links. But there is a problem with the links in the HTML content, it is not opening the links in the browser when it is clicked.

This is my code.

Container(
                              color: Colors.white,
                              padding: EdgeInsets.only(top: 10, right: 10, bottom: 10, left: 10),
                              child: Html(
                                  data: htmlContent,
                                  onLinkTap: (link) {
                                    launch(link);
                                  },
                              ))

When I click on it, it is not working.

I imported this library at the top.

import 'package:url_launcher/url_launcher.dart';

What is wrong with my code and how can I fix it?

3 Answers

Opening links in HTML works for me like this:

Html(
  data: 'This is some <a href="https://pub.dev/packages/url_launcher">link</a>',
  onLinkTap: (url) async {
    if (await canLaunch(url)) {
      await launch(
        url,
      );
    } else {
      throw 'Could not launch $url';
    }
  },
)

Note that I first await the canLaunch method before using launch to open my link.

What was your link? Would you provide us an example? Thanks!

 Html(
  data: dataHTML,
  onLinkTap: (url, _, __, ___) async {
    if (await canLaunch(url!)) {
      await launch(
        url,
      );
    } 
  },
);

In recent versions, flutter_html, when using this event, requests more parameters that fulfill a specific task which is detailed in the documentation, but if the intention is only to launch the Urls, they can do it this way, do not forget to add the <queries> in the AndroidManifest if your app uses API 30 or higher that you specify in using url_launcher

onLinkTap: (url) async {
    if (await canLaunch(url)) {
      await launch(
        url,
      );
    } else {
      throw 'Could not launch $url';
    }
  },

Also don't forgot to add this in your Manifest file

       <queries>
        <intent>
            <action android:name="android.intent.action.VIEW" />
            <data android:scheme="https" />
        </intent>
        <intent>
            <action android:name="android.intent.action.DIAL" />
            <data android:scheme="tel" />
        </intent>
        <intent>
            <action android:name="android.intent.action.SEND" />
            <data android:mimeType="*/*" />
        </intent>
    </queries>
Related