Created
October 15, 2018 10:28
-
-
Save analogic/5f02b52761cb506d140e8870f99592b7 to your computer and use it in GitHub Desktop.
Flutter method to create text with autodetected links
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
RichText _autolink(String text, BuildContext context) { | |
final themeData = Theme.of(context); | |
if (text == null) { | |
return RichText(text: TextSpan(text: "")); | |
} | |
final linkStyle = themeData.textTheme.body2.copyWith(color: themeData.accentColor, decoration: TextDecoration.underline); | |
final textStyle = themeData.textTheme.body2.copyWith(color: Colors.grey, fontStyle: FontStyle.normal); | |
final exp = new RegExp(r"^(?:http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?$"); | |
final chunks = text.split(" "); | |
final spans = new List<TextSpan>(); | |
String current = ''; | |
for (int i = 0; i < chunks.length; i++) { | |
if (exp.hasMatch(chunks[i])) { | |
if (current.length > 0) { | |
spans.add(TextSpan(style: textStyle, text: "$current ")); | |
current = ''; | |
} | |
spans.add(TextSpan(style: linkStyle, text: chunks[i], recognizer: TapGestureRecognizer()..onTap = () { | |
launch(chunks[i]); | |
})); | |
} else { | |
current += " ${chunks[i]}"; | |
} | |
} | |
if (current.length > 0) { | |
spans.add(TextSpan(style: textStyle, text: current)); | |
} | |
return RichText( | |
text: TextSpan( | |
children: spans | |
) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment