Press "Enter" to skip to content

Flutter : Create Hyperlink URL for a Text

Links to external sites or apps are very common in all application developments. On this tutorial let’s learn, in Flutter, how to make a text as a clickable hyperlink or create direct URL that opens in your default browser or external application like opening a normal http link.

There are many methods for this. Here we make possible by importing url_launcher package.

Import url_launcher Package

url_launcher is one of the popular package used for creating Hyperlinks.

Add url_launcher package on your pubspec.yaml file.

  url_launcher: ^6.0.9

check latest version on the site. Currently latest version is 6.0.9

Learn here how to import and use a package on flutter

Using url_launcher package

import url_laucher plugin on your dart file that you want create hyperlinks.

import 'package:url_launcher/url_launcher.dart';

Create a function for url_laucher

Create a function inside the state class.

_launchURL(String url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }

Where ‘url’ is the URL that you want to make hyperlink.

Add Permission on AndroidManifest File

<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>
Add query all package permission on android manifest for Flutter

Make Hyperlink for a Text

You can make hyperlink for a text by calling _launchURL function on an event like onPressed, onTap, etc.

 TextButton(    
            child: Text("Go to Google"),
                  onPressed: () {
                    _launchURL("http://www.google.com");
                  },
           ),

Complete Working Code

import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';

void main()
{
  runApp(
    MaterialApp(
      home: MyApp(),
    ),
  );
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  _launchURL(String url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: new AppBar(
          title: new Text("My First Flutter App"),
        ),
        body: Container(
          child:
              Center(
                child:  TextButton(
                  child: Text("Go to Google"),
                  onPressed: () {
                    _launchURL("http://www.google.com");
                  },
                ),
              )
        )
    );
  }
}

Output

Flutter Create Hyperlink URL for a Text

Video Tutorial

Here you can watch full video tutorial

Be First to Comment

Leave a Reply