我正在试着在Flutter中做一个内联链接的小工具。为此,我制作了一个名为EmbeddedUrlText的小部件,它接受一个字符串。对于超链接,我在需要突出显示为链接的文本周围添加了一个标记。我使用的是一个内部有文本跨度的RichText小部件。链接(TextSpans)有一个监听点击的TapGestureRecognizer。我想要获取TextSpan中的文本,或者以某种方式获取所单击的文本跨度。
该小部件的调用方式如下
EmbeddedUrlText("This is the <l>link</l>", ["https://www.google.com"])因此,当“链接”这个词被点击时,google.com就会打开。链接的索引将打开适当的链接索引。
到目前为止,如果给定了链接列表,则链接将突出显示并显示,如果是特定索引,还会打开链接,但TapGestureRecognizer不会返回有关单击了哪个文本跨度的任何信息。请推荐我能找到的任何方法。
以下是小部件的代码:
class EmbeddedUrlText extends StatelessWidget {
List<TextSpan> widgets = [];
//Keeps a count of the number of links in the text.
var linksAdded = 0;
EmbeddedUrlText(String text, List<String> links,
{TextStyle style = const TextStyle(color: Colors.black)}) {
//Find text between <l></l> tags and add it as a separate text span
String widgetText = "";
for (var i = 0; i < text.length; i++) {
// Beyond this limit, a complete <l> tag cannot fit, hence do not check for tags.
if (i < text.length - 6) {
if (text[i] == "<" && text[i + 1] == "l" && text[i + 2] == ">") {
widgets.add(TextSpan(
text: widgetText, style: TextStyle(color: Colors.black)));
widgetText = "";
i += 3;
while (text[i] != "<" && i < text.length) {
widgetText = widgetText + text[i];
i++;
}
i += 3;
widgets.add(
TextSpan(
style: TextStyle(color: Colors.blue),
text: widgetText,
recognizer: TapGestureRecognizer()..onTap = () {
//I want to open URL of the clicked index of TextSpan
}
)
);
widgetText = "";
} else {
widgetText = widgetText + text[i];
}
} else {
widgetText = widgetText + text[i];
}
}
// At the end add the remaining text to the text
widgets.add(TextSpan(text: widgetText, style: TextStyle(color: Colors.black)));
}
@override
Widget build(BuildContext context) {
return RichText(text: TextSpan(children: widgets));
}
_launchURL(String url) async {
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
}https://stackoverflow.com/questions/51404841
复制相似问题