232

I would like to create a hyperlink to display in my Flutter app.

The hyper link should be embedded in a Text or similar text views like:

The last book bought is <a href='#'>this</a>

Any hint to do this?

TaylorR
  • 3,746
  • 5
  • 25
  • 42

15 Answers15

325

Just wrap an InkWell around a Text widget and supply an UrlLauncher (from the service library) to the onTap attribute. Install UrlLauncher as a Flutter package before using it below.

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


void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('UrlLauncher'),
        ),
        body: new Center(
          child: new InkWell(
              child: new Text('Open Browser'),
              onTap: () => launch('https://docs.flutter.io/flutter/services/UrlLauncher-class.html')
          ),
        ),
      ),
    );
  }
}

You can supply a style to the Text widget to make it look like a link.

Update

After looking into the issue a little I found a different solution to implement the 'in line' hyperlinks you asked for. You can use the RichText Widget with enclosed TextSpans.

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

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('UrlLauchner'),
        ),
        body: new Center(
          child: new RichText(
            text: new TextSpan(
              children: [
                new TextSpan(
                  text: 'This is no Link, ',
                  style: new TextStyle(color: Colors.black),
                ),
                new TextSpan(
                  text: 'but this is',
                  style: new TextStyle(color: Colors.blue),
                  recognizer: new TapGestureRecognizer()
                    ..onTap = () { launch('https://docs.flutter.io/flutter/services/UrlLauncher-class.html');
                  },
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

This way you can actually highlight one word and make a hyperlink out of it ;)

geisterfurz007
  • 5,292
  • 5
  • 33
  • 54
Rainer Wittmann
  • 7,528
  • 4
  • 20
  • 34
  • 15
    UrlLauncher is no longer part of flutter, it was moved to [a plugin and API changed](https://pub.dartlang.org/packages/url_launcher). – Josef Adamcik May 09 '18 at 17:40
  • 10
    Also we need to add imports: import 'package:flutter/gestures.dart'; import 'package:url_launcher/url_launcher.dart'; – Alex Pliutau Aug 13 '18 at 03:58
  • 16
    You are not handling the lifecycle of your `TapGestureRecognizer` correctly. You have to call `dispose()` method when `RichText` is no longer used. See here: https://api.flutter.dev/flutter/painting/TextSpan/recognizer.html – Alex Semeniuk Aug 20 '19 at 15:05
  • 1
    @AlexSemeniuk In your example they are using a StatefulWidget, in the answer above it is a StatelessWidget. Are you sure we need to dispose the the case of a StatelessWidget? – Corey Cole Oct 08 '19 at 00:27
  • 6
    @CoreyCole `StatelessWidget` will not magically dispose your `TapGestureRecognizer` for you. In fact, using `StatelessWidget` in this scenario is incorrect, since you can not dispose your rsources this way. And yes, you _absolutely_ need to call `dispose()` method of `TapGestureRecognizer`, since it runs the internal timer which needs to be stopped. – Alex Semeniuk Oct 08 '19 at 11:38
  • Thanks Alex, yes I definitely noticed memory leak problems in logcat when I tried using a StatelesWidget for this – Corey Cole Oct 11 '19 at 22:25
  • Simpler than RichText: `new InkWell(child: new Text('linktext', style: new TextStyle(color: Colors.blue, decoration: TextDecoration.underline),), onTap: () => {})),` – Eugene Gr. Philippov Sep 21 '20 at 09:59
  • Gosh, flutter changed another api and broke working code? Who'da thought...? (sigh) – ChrisH Jun 07 '22 at 21:24
  • the launch(' ') is deprecated use launchUrl(Uri.parse(' ')) the old: ..onTap = () { launch('https://docs.flutter.io/flutter/services/UrlLauncher-class.html'); }, New ..onTap = () { launchUrl(Uri.parse('https://androidride.com')); }, – Ridha Rezzag Jun 09 '22 at 14:51
  • The URL in the example gives a HTTP 404. Also, the new method seems to be `launchUrlString()` instead of `launch()`. – Thomas Weller Mar 28 '23 at 09:27
  • `new` is not needed in Dart these days... – Luke Hutchison Apr 26 '23 at 06:05
105

Flutter doesn't have built-in hyperlink support but you can fake it yourself. There's an example in the Gallery's drawer.dart. They use a RichText widget containing a coloured TextSpan, which has a recognizer attribute to handle taps:

        RichText(
          text: TextSpan(
            children: [
              TextSpan(
                style: bodyTextStyle,
                text: seeSourceFirst,
              ),
              TextSpan(
                style: bodyTextStyle.copyWith(
                  color: colorScheme.primary,
                ),
                text: repoText,
                recognizer: TapGestureRecognizer()
                  ..onTap = () async {
                    final url = 'https://github.com/flutter/gallery/';
                    if (await canLaunch(url)) {
                      await launch(
                        url,
                        forceSafariVC: false,
                      );
                    }
                  },
              ),
              TextSpan(
                style: bodyTextStyle,
                text: seeSourceSecond,
              ),
            ],
          ),

enter image description here

enter image description here

CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
Collin Jackson
  • 110,240
  • 31
  • 221
  • 152
84

Update (Android >= 11):

  • iOS configuration:

    Open info.plist file and add:

    <key>LSApplicationQueriesSchemes</key>
    <array>
      <string>https</string>
    </array>
    
  • Android configuration:

    Open AndroidManifest.xml file located in app/src/main and add the following at the root:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android">
    
       <!-- Add this query -->
        <queries>
            <intent>
                <action android:name="android.intent.action.VIEW" />
                <data android:scheme="https" />
            </intent>
        </queries>
    
        <application ... />
    
    </manifest>
    

Flutter code:

Simply wrap your Text in a GestureDetector or InkWell and handle click in onTap() using url_launcher package.

InkWell(
  onTap: () => launchUrl(Uri.parse('https://www.google.com')),
  child: Text(
    'Click here',
    style: TextStyle(decoration: TextDecoration.underline, color: Colors.blue),
  ),
)

Screenshot:

enter image description here

CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
24

You can use package flutter_linkify
https://pub.dev/packages/flutter_linkify
Just want to provide another option.
Package will divide your text and highlight http/https automatically
Combine plugin url_launcher you can launch url
You can check example below:

enter image description here

full code below

import 'package:flutter/material.dart';
import 'package:flutter_linkify/flutter_linkify.dart';
import 'dart:async';

import 'package:url_launcher/url_launcher.dart';

void main() => runApp(new LinkifyExample());

class LinkifyExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'flutter_linkify example',
      home: Scaffold(
        appBar: AppBar(
          title: Text('flutter_linkify example'),
        ),
        body: Center(
          child: Linkify(
            onOpen: _onOpen,
            text: "Made by https://cretezy.com \n\nMail: example@gmail.com \n\n  this is test http://pub.dev/ ",
          ),
        ),
      ),
    );
  }

  Future<void> _onOpen(LinkableElement link) async {
    if (await canLaunch(link.url)) {
      await launch(link.url);
    } else {
      throw 'Could not launch $link';
    }
  }
}
chunhunghan
  • 51,087
  • 5
  • 102
  • 120
  • How can you have 2 links on same widget? Like for example "by clicking this you accept terms of use and privacy policy" where we need to have them together – Dani Nov 14 '20 at 09:05
  • Awesome package. Saves a lot of boiler plate code – Sisir May 01 '21 at 12:56
  • @Dani you can add as many links as you want because the flutter linkify package treats every link different. I have tested the above snippet for more than 1 link and it works perfectly – Roopak May 22 '21 at 13:01
  • Thanks. That is what I was searching for – Mr. ZeroOne Jul 06 '21 at 21:23
  • The API has changed so the example above doesn't work anymore - see https://github.com/Cretezy/flutter_linkify/issues/112 for an example using the new `canLaunchUrl` and `launchUrl` instead. – abulka Oct 26 '22 at 00:45
8

flutter link widget

In Flutter 2.0, the Link widget was introduced. Use this widget to launch webpages and also navigate to new screens in your app. you need to use the url_launcher package before using it.

url_launcher: ^6.0.8

For More Information

Link(
              uri: Uri.parse('https://androidride.com'),
              //target: LinkTarget.self,
              builder: (context, followLink) {
                return RichText(
                  text: TextSpan(children: [
                    TextSpan(
                      text: 'Click here: ',
                      style: TextStyle(
                        fontSize: 20,
                        color: Colors.black,
                      ),
                    ),
                    TextSpan(
                      text: 'AndroidRide',
                      style: TextStyle(
                        color: Colors.blue,
                        decoration: TextDecoration.underline,
                        fontWeight: FontWeight.bold,
                        fontSize: 21,
                      ),
                      recognizer: TapGestureRecognizer()
                        ..onTap = followLink,
                    ),
                  ]),
                );
              }),
        ),
        SizedBox(
          height: 20,
        ),
        Link(
          uri: Uri.parse('/second'),
          builder: (context, followLink) {
            return InkWell(
              onTap: followLink,
              child: Text(
                'Go to Second Screen',
                style: TextStyle(
                  fontSize: 20,
                  color: Colors.blue,
                  decoration: TextDecoration.underline,
                ),
              ),
            );
          },
        ),
Vijay Ram
  • 385
  • 5
  • 12
7

If you want to make it look even more like a link, you can add underline:

new Text("Hello Flutter!", style: new TextStyle(color: Colors.blue, decoration: TextDecoration.underline),)

and the result:

enter image description here

bartektartanus
  • 15,284
  • 6
  • 74
  • 102
7

You can use Link Text https://pub.dev/packages/link_text and use it like

 final String _text = 'Lorem ipsum https://flutter.dev\nhttps://pub.dev'; 
 @override
 Widget build(BuildContext context) {
 return Scaffold(
     body: Center(
      child: LinkText(
        text: _text,
        textAlign: TextAlign.center,
      ),
    ),
  );
}
  • Under Linux `flutter pub get` for it fails with `Unable to find a plugin.vcxproj for plugin "url_launcher_windows"` – Eugene Gr. Philippov Sep 21 '20 at 09:51
  • This is limited only to making links clickable. not a word, pointing to a link – chitgoks Jul 20 '21 at 01:57
  • If the url itself is allowed to be visible, this is hands down the easiest solution to implement instead of an existing Text widget. If you need the url not visible but as a link behind other text, this does not work as is. Bonus: it also makes AlertDialog links clickable. – DaReal Nov 13 '22 at 22:44
7

Adding one more simple and neat trick because the above ones are over-complicated for some use cases. I did it using RichText - WidgetSpan, TextButton and URL launcher package. Just modify the below example block according to your needs.

Result: Result

Code:

class UserAgreementText extends StatelessWidget {
  const UserAgreementText({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
          child: RichText(
            textAlign: TextAlign.center,
            text: TextSpan(
              text: 'By logging in, you accept our ',
              style: Theme.of(context).textTheme.bodySmall,
              children: const <InlineSpan>[
                WidgetSpan(
                  alignment: PlaceholderAlignment.baseline,
                  baseline: TextBaseline.alphabetic,
                  child: LinkButton(
                      urlLabel: "Terms and Conditions",
                      url: "https://example.com/terms-and-conditions"),
                ),
                TextSpan(
                  text: ' and ',
                ),
                WidgetSpan(
                  alignment: PlaceholderAlignment.baseline,
                  baseline: TextBaseline.alphabetic,
                  child: LinkButton(
                      urlLabel: "Privacy Policy",
                      url: "https://example.com/privacy-policy"),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
}

link_button.dart

class LinkButton extends StatelessWidget {
  const LinkButton({Key? key, required this.urlLabel, required this.url})
      : super(key: key);

  final String urlLabel;
  final String url;

  Future<void> _launchUrl(String url) async {
    final Uri uri = Uri.parse(url);

    if (!await launchUrl(uri)) {
      throw 'Could not launch $uri';
    }
  }

  @override
  Widget build(BuildContext context) {
    return TextButton(
      style: TextButton.styleFrom(
        padding: EdgeInsets.zero,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(0),
        ),
        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
        visualDensity: VisualDensity.compact,
        minimumSize: const Size(0, 0),
        textStyle: Theme.of(context).textTheme.bodySmall,
      ),
      onPressed: () {
        _launchUrl(url);
      },
      child: Text(urlLabel),
    );
  }
}

Note: If you get an error related to calling launchUrl, make sure you install the URL launcher package and then rebuild your application.

Aaron Krauss
  • 7,494
  • 1
  • 17
  • 19
Deepanshu
  • 890
  • 5
  • 18
  • 1
    If you receive the error `flutter Intrinsics are not available for PlaceholderAlignment.baseline` then remove `alignment` and `baseline` from `WidgetSpan`. – Chuck Batson Dec 01 '22 at 18:29
5

You could use the flutter_html plugin if you want to have more advanced text capabilities:

Html(
  data: 'The last <i><u><b>book</b></u></i> bought is <a href="#">this</a>',
  onLinkTap: (url, context, attrs, element) {
    // Handle link tapped...
  },
)

This is just the tip of the iceberg of capabilities with this plugin.

Just a thought: You could even host parts of your flutter app online as html and render them in flutter as widgets with this plugin.

Pierre
  • 8,397
  • 4
  • 64
  • 80
2

The answers to this question that suggest using RichText with a TextSpan + GestureRecognizer are all functionally correct, but from the UX perspective, they do not provide feedback to the user responding to the touch. To maintain consistency with other Material widgets, you could use a similar approach, but use a WidgetSpan + InkWell instead.

This example uses the url_launcher package and an unstyled InkWell, but you can customize as you see fit:

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

class TextWithLink extends StatelessWidget {
  const TextWithLink({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    const textStyle = TextStyle(color: Colors.black); // default style for all text
    return RichText(
      text: TextSpan(
        style: textStyle,
        children: [
          const TextSpan(
            text: 'The last book bought is ',
          ),
          WidgetSpan(
              alignment: PlaceholderAlignment.middle,
              child: InkWell(
                  onTap: () => _launchUrl('https://url-to-launch.com'),
                  child: Text('this',
                      style: textStyle.merge(const TextStyle(
                          color: Colors.blue, fontWeight: FontWeight.bold))))), // override default text styles with link-specific styles
        ],
      ),
    );
  }

  _launchUrl(String url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }
}
hunteros
  • 1,137
  • 11
  • 20
2

I see a lot of verbose answers here that don't work so well.

If you want to do this from user generated content you can use https://pub.dev/packages/flutter_markdown

This works on all platforms and is highly dynamic and customisable.

Oliver Dixon
  • 7,012
  • 5
  • 61
  • 95
1

An alternative (or not) way to put clickable links in your app (for me it just worked that way):

1 - Add the url_launcher package in your pubspec.yaml file

(the package version 5.0 didn't work well for me, so I'm using the 4.2.0+3).

dependencies:
  flutter:
    sdk: flutter
  url_launcher: ^4.2.0+3

2 - Import it and use as below.

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

void main() {
  runApp(MaterialApp(
    title: 'Navigation Basics',
    home: MyUrl(),
  ));
}

class MyUrl extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Url Launcher'),
      ),
      body: Center(
        child: FlatButton(
          onPressed: _launchURL,
          child: Text('Launch Google!',
              style: TextStyle(fontSize: 17.0)),
        ),
      ),
    );
  }

  _launchURL() async {
    const url = 'https://google.com.br';
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }
}
Fellipe Sanches
  • 7,395
  • 4
  • 32
  • 33
  • If need a hyperlink between some text, you can use a `FlatButton` with same background and text colors as the rest of your texts, so format it whith TextDecoration.underline as the bartektartanus showed above... – Fellipe Sanches Mar 12 '19 at 19:56
1

Here is a turn-key package https://pub.dev/packages/link_text

child: LinkText(
  'Hello check http://google.com',
  textStyle: ...,
),

Safer to use a library for this kind of complexity

Pros:

  • takes in the entire string as a single param
  • parses the links and renders them into the UI as clickable , inline with the non-clickable text
  • no complex RichText structure required
Gene Bo
  • 11,284
  • 8
  • 90
  • 137
1

Let's separate this question to 2 things:

  1. How to embed a link inside a line of text
  2. How to launch a url in an external browser/window

For #2: As posted here - use url_launcher

For #1: I think using RichText is an overkill for this, I simply used Text's and TextButton, in a Wrap container like so:

Wrap(
  alignment: WrapAlignment.center,
  runAlignment: WrapAlignment.center,
  crossAxisAlignment: WrapCrossAlignment.center,
  children: [
    const Text('The last book bought is'),
    TextButton(
      onPressed: () {
        launchUrl(Uri.parse('https://someurl'), mode: LaunchMode.externalApplication);
      },
      child: const Text('this')),
  ],
)
Shahar Hajdu
  • 315
  • 2
  • 4
1

Somehow I liked to create my own solution to this to see what happens so here is the result,

TextSpan linkify(BuildContext context, String rawText) {
  final spans =
      rawText.split(RegExp('(?=https?://|mailto:|tel:)')).indexed.expand((e) {
    final (i, chunk) = e;
    final index = i == 0 ? 0 : chunk.indexOf(RegExp('\\s|\\)|\$'));
    final link = chunk.substring(0, index);
    return [
      if (i != 0)
        TextSpan(
          text: link.replaceFirst(RegExp('^(mailto|tel):'), ''),
          style: Theme.of(context).textTheme.bodySmall?.copyWith(
                decoration: TextDecoration.underline,
                color: Theme.of(context).colorScheme.primary,
              ),
          recognizer: TapGestureRecognizer()
            ..onTap = () => launchUrl(Uri.parse(link)),
        ),
      TextSpan(
        text: chunk.substring(index),
        style: Theme.of(context).textTheme.bodySmall,
      ),
    ];
  });
  return TextSpan(children: [...spans]);
}

Example:

const rawText = '''Here is a sample test http://example.com (https://example.com)

Contact: mailto:example@example.com and tel:+1-555-5555-555

https://example.com''';

RichText(text: linkify(context, rawText))

output from raw code

Note the tel: and mailto: are removed, one possibly could find mail and telephone themselves but I preferred to mark them explicitly then remove them.

Ebrahim Byagowi
  • 10,338
  • 4
  • 70
  • 81