linkText function
Implementation
Widget linkText(String text, TextStyle style) {
final urlRegExp = RegExp(r'(https?:\/\/[^\s]+)', caseSensitive: false);
final spans = <TextSpan>[];
final matches = urlRegExp.allMatches(text);
int start = 0;
for (final match in matches) {
if (match.start > start) {
spans.add(
TextSpan(text: text.substring(start, match.start), style: style),
);
}
final url = match.group(0)!;
spans.add(
TextSpan(
text: url,
style: style.copyWith(
color: Colors.blue,
decoration: TextDecoration.underline,
),
recognizer: TapGestureRecognizer()
..onTap = () async {
final uri = Uri.parse(url);
if (await canLaunchUrl(uri)) {
await launchUrl(uri, mode: LaunchMode.externalApplication);
}
},
),
);
start = match.end;
}
if (start < text.length) {
spans.add(TextSpan(text: text.substring(start), style: style));
}
return SelectableText.rich(TextSpan(children: spans));
}