How to create Hyperlink for Text in Flutter
In most of the mobile application, there are links which redirect the users to some external website for further read about particular section or an article. Therefore we will need a way to accomplish this in our Flutter app.
There is no build-in widget to add a link to text in Flutter. But there are some work-round which we can use to accomplish the same goal.
Add the plugin
First, you need a url_launcher plugin if we need to redirect the user to the external website. Load the pubspec.yaml and apply that plugin
url_launcher: ^5.7.5
Run the following command to get the plugin or your project
flutter pub get
Next import the plugin where you want to use that.
import 'package:url_launcher/url_launcher.dart';
Load URL when pressing the text
Usually when we add ing a link like “read more” we will add it as a part of an existing paragraph. For that, we have to use the RichText widget which allows using TextSpan widget to separate some wording to add the unique style.
For one TextSpan you can make the text style looks like the link by adding the blue colour and you can use recogniser property to set a Gesture detector for a particular text. It will help to capture the text click in the widget. In there you can use the launch method to load the particular URL when someone Tap on the text.
RichText(
text: TextSpan(
children: [
TextSpan(
style: defaultText,
text: "To learn more "
),
TextSpan(
style: linkText,
text: "Click here",
recognizer: TapGestureRecognizer()..onTap = () async{
var url = "https://www.youtube.com/channel/UCwxiHP2Ryd-aR0SWKjYguxw?view_as=subscriber";
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
),
]
))
Turn Text URL to Clickable link using linkify
linkify Flutter plugin can turn text URL and email to a clickable inline text.
First, add flutter_linkify plugin to your project.
dependencies:
flutter_linkify: ^3.1.3
Next import to the file which you are going to implement the code.
import 'package:flutter_linkify/flutter_linkify.dart';
Now you can directly use the widget like below
Linkify(
onOpen: (link) {
print("Linkify link = ${link.url}");
},
text: "Linkify click - https://www.youtube.com/channel/UCwxiHP2Ryd-aR0SWKjYguxw",
style: TextStyle(color: Colors.blue),
linkStyle: TextStyle(color: Colors.green),
),
onOpen callback will pass the link and you can perform any action from there. In this case, I only print the link in the console, but you can use the launch method to launch the actual URL in a browser.
How to show http:// or https:// in the link text
You can enable humanize option to true to make this happen.
options: LinkifyOptions(humanize: false),
Remove www from the link
options: LinkifyOptions(removeWww: true)
Originally published at https://mightytechno.com on October 23, 2020.