首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过TapGestureRecognizer获取有关TextSpan的信息

如何通过TapGestureRecognizer获取有关TextSpan的信息
EN

Stack Overflow用户
提问于 2018-07-18 22:38:37
回答 0查看 1.2K关注 0票数 1

我正在试着在Flutter中做一个内联链接的小工具。为此,我制作了一个名为EmbeddedUrlText的小部件,它接受一个字符串。对于超链接,我在需要突出显示为链接的文本周围添加了一个标记。我使用的是一个内部有文本跨度的RichText小部件。链接(TextSpans)有一个监听点击的TapGestureRecognizer。我想要获取TextSpan中的文本,或者以某种方式获取所单击的文本跨度。

该小部件的调用方式如下

代码语言:javascript
复制
EmbeddedUrlText("This is the <l>link</l>", ["https://www.google.com"])

因此,当“链接”这个词被点击时,google.com就会打开。链接的索引将打开适当的链接索引。

到目前为止,如果给定了链接列表,则链接将突出显示并显示,如果是特定索引,还会打开链接,但TapGestureRecognizer不会返回有关单击了哪个文本跨度的任何信息。请推荐我能找到的任何方法。

以下是小部件的代码:

代码语言:javascript
复制
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';
    }
  }

}
EN

回答

页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51404841

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档