Skip to content

Instantly share code, notes, and snippets.

@rekire
Created March 28, 2022 20:33
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 rekire/0b957f62a5d55cb72e4ff6a23bd287d4 to your computer and use it in GitHub Desktop.
Save rekire/0b957f62a5d55cb72e4ff6a23bd287d4 to your computer and use it in GitHub Desktop.
A very simple url parser for RichText written in dart
static int findEnd(String string, int start) {
int index = string.indexOf(">", start);
if (index == -1) {
return string.length -1;
} else {
return index;
}
}
static List<TextSpan> parseHtml(String html) {
List<TextSpan> parts = <TextSpan>[];
int pos = 0;
if (!html.contains("<a", pos)) {
parts = [TextSpan(text: html)];
} else {
TextStyle linkStyle = const TextStyle(color: Colors.blue);
do {
int tagStart = html.indexOf("<a", pos);
if (tagStart == -1) {
parts.add(TextSpan(text: html.substring(pos, html.length)));
pos = html.length;
} else {
parts.add(TextSpan(text: html.substring(pos, tagStart)));
int tagEnd = findEnd(html, tagStart) + 1;
if (tagEnd > tagStart) {
String tag = html.substring(tagStart, tagEnd);
int attrStart = tag.indexOf("href");
if (attrStart > 0) {
int valueStart = tag.indexOf("\"") + 1;
int valueEnd = tag.indexOf("\"", valueStart);
String target = tag.substring(valueStart, valueEnd);
int close = html.indexOf("</a>", pos);
if (close == -1) throw Exception("</a> expected");
parts.add(TextSpan(
text: html.substring(tagEnd, close),
style: linkStyle,
recognizer: TapGestureRecognizer()
..onTap = () {
print('Click on ' + target);
},
));
pos = close + 4;
}
}
}
} while (pos < html.length);
}
return parts;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment