Skip to content

Instantly share code, notes, and snippets.

@harshapulikollu
Forked from putraxor/rich_text_view.dart
Created June 30, 2019 05:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harshapulikollu/a5a4297a6ecc992674dad4044303e01e to your computer and use it in GitHub Desktop.
Save harshapulikollu/a5a4297a6ecc992674dad4044303e01e to your computer and use it in GitHub Desktop.
Flutter rich text view with clickable hyperlink
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart' as launcher;
///TODO: check performance impact bro !!!
class LinkTextSpan extends TextSpan {
LinkTextSpan({TextStyle style, String url, String text})
: super(
style: style,
text: text ?? url,
recognizer: new TapGestureRecognizer()
..onTap = () => launcher.launch(url));
}
class RichTextView extends StatelessWidget {
final String text;
RichTextView({@required this.text});
bool _isLink(String input) {
final matcher = new RegExp(
r"(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)");
return matcher.hasMatch(input);
}
@override
Widget build(BuildContext context) {
final _style = Theme.of(context).textTheme.body2;
final words = text.split(' ');
List<TextSpan> span = [];
words.forEach((word) {
span.add(_isLink(word)
? new LinkTextSpan(
text: '$word ',
url: word,
style: _style.copyWith(color: Colors.blue))
: new TextSpan(text: '$word ', style: _style));
});
if (span.length > 0) {
return new RichText(
text: new TextSpan(text: '', children: span),
);
} else {
return new Text(text);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment