In Flutter, if you want a text with a clickable hyperlink inside it, you typically use a RichText
widget with a TextSpan
, and you add a gesture recognizer to detect taps.
Here’s a simple example:
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
class HyperlinkTextExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Hyperlink in Text')),
body: Center(
child: RichText(
text: TextSpan(
text: 'Click ',
style: TextStyle(color: Colors.black, fontSize: 18),
children: [
TextSpan(
text: 'here',
style: TextStyle(color: Colors.blue, decoration: TextDecoration.underline),
recognizer: TapGestureRecognizer()
..onTap = () {
// Handle the tap - e.g., open a URL
print('Hyperlink tapped!');
},
),
TextSpan(
text: ' to learn more.',
),
],
),
),
),
);
}
}
If you want to open a real URL, you can use the url_launcher
– package.
Quick example for launching a URL:
import 'package:url_launcher/url_launcher.dart';
void _launchUrl() async {
final url = Uri.parse('https://example.com');
if (await canLaunchUrl(url)) {
await launchUrl(url);
} else {
throw 'Could not launch $url';
}
}
RichText
is a very powerful widget that allows you to display text with multiple styles in a single block. Unlike a simple Text
widget, RichText
lets you customize parts of the text differently (like bolding one word, coloring another, etc.).
Here are the main features of RichText
:
1. Multiple Text Styles
You can apply different fonts, colors, sizes, weights, decorations (underline, strikethrough, etc.) to different parts of the text.
2. Inline Formatting
By using a tree of TextSpan
s inside the RichText
, you can format each span independently.
3. Fine Control over Text Layout
It gives you more control over things like text alignment, overflow, max lines, scaling, and soft wrapping.
4. Accessibility Support
Proper semantics are created for accessibility readers (like TalkBack or VoiceOver).
5. Performance Optimized
Flutter optimizes how RichText
is rendered internally, so even complex styled texts are rendered efficiently.
7. Directionality
Supports left-to-right (LTR) and right-to-left (RTL) text based on the textDirection
.
Basic Example:
RichText(
text: TextSpan(
text: 'Hello ',
style: TextStyle(color: Colors.black, fontSize: 20),
children: <TextSpan>[
TextSpan(
text: 'bold',
style: TextStyle(fontWeight: FontWeight.bold)),
TextSpan(
text: ' and ',
style: TextStyle(fontStyle: FontStyle.italic)),
TextSpan(
text: 'colorful!',
style: TextStyle(color: Colors.red)),
],
),
)
RichText gives you the possibility to render HTML like content, but execute something from within the app. If you need to render more tags and content – check out some of the Flutter HTML Solutions.