loading...
Cover image for Hyperlink Widget on Flutter

Hyperlink Widget on Flutter

guimg profile image guim ・2 min read

This tutorial is about how to open a web browser from our app. Like HTML hyperlinks do. To do so, we'll use the package url_launcher, which you can find here.

Add the package to your project

To add url_launcher package into our project, we have to include it into our pubspec.yaml file dependencies, like this:

dependencies:
  flutter:
    sdk: flutter

  url_launcher: ^5.0.2

Now we have to tell Flutter to download all dependencies. Open a terminal, go to the app folder, and type:

flutter packages get

Creating the Hyperlink Widget

Inside the folder lib, create a new folder called widgets. Inside this widgets folder, create a new file called Hyperlink.dart. This file will look like this:

import 'package:flutter/material.dart';

import 'package:url_launcher/url_launcher.dart';

class Hyperlink extends StatelessWidget {
  final String _url;
  final String _text;

  Hyperlink(this._url, this._text);

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

  @override
  Widget build(BuildContext context) {
    return InkWell(
      child: Text(
        _text,
        style: TextStyle(decoration: TextDecoration.underline),
      ),
      onTap: _launchURL,
    );
  }
}

Remember to import the url_launcher package. This widget gets two strings, the url and the text to show. And it creates a InkWell widget to manage the onTap event and call the url launcher.

Using the Widget

Now in our main.dart file we can call this widget. Remember to import the file from the widgets folder.

import 'package:flutter/material.dart';

import './widgets/Hyperlink.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Hyperlink tutorial',
      theme: ThemeData(
          brightness: Brightness.dark
          ),
      home: Scaffold(
        body: Center(
          child: Hyperlink('https://guimgonzalez.business/', 'Awesome website!'),
        ),
      ),
    );
  }
}

This is it! If you have any doubt or code recommendation please leave it in the comments below. Thanks.

Posted on by:

guimg profile

guim

@guimg

Software Engineer

Discussion

markdown guide