【问题标题】:Make specific parts of a text clickable in flutter [duplicate]在颤动中使文本的特定部分可点击[重复]
【发布时间】:2020-01-28 10:23:18
【问题描述】:

我想让文本的一部分成为可点击的,这样我就可以在其上调用函数。我还想控制可点击文本的样式。在最好的情况下,我还可以将可点击区域的大小增加到例如 42 像素。

我已经研究了 flutter_linkify 和 linkify,但这不是我想要的。我很好奇 Flutter 库中是否已经有一个包,甚至是内置的。

【问题讨论】:

标签: text flutter dart clickable


【解决方案1】:

RichTextTextSpanGestureRecognizer 一起使用。使用GestureRecognizer,您可以检测点击双击长按等。

Widget build(BuildContext context) {
    TextStyle defaultStyle = TextStyle(color: Colors.grey, fontSize: 20.0);
    TextStyle linkStyle = TextStyle(color: Colors.blue);
    return RichText(
      text: TextSpan(
        style: defaultStyle,
        children: <TextSpan>[
          TextSpan(text: 'By clicking Sign Up, you agree to our '),
          TextSpan(
              text: 'Terms of Service',
              style: linkStyle,
              recognizer: TapGestureRecognizer()
                ..onTap = () {
                  print('Terms of Service"');
                }),
          TextSpan(text: ' and that you have read our '),
          TextSpan(
              text: 'Privacy Policy',
              style: linkStyle,
              recognizer: TapGestureRecognizer()
                ..onTap = () {
                  print('Privacy Policy"');
                }),
        ],
      ),
    );
  }

【讨论】:

  • 效果很好!请注意,您需要 import 'package:flutter/gestures.dart'; 才能使用此功能。
  • 你能解释一下..这个符号吗,我以前没见过。
  • .. 表示法允许您调用特定方法,然后返回调用该方法的原始对象,通常用于我们想要以级联方式调用同一对象上的多个方法时
  • 我有一个从数据库中获取的字符串,例如nice concept of help/support - https://support.google.com/firebase?authuser=0#topic=6399725 现在告诉我如何将这个 URL 从这个字符串转换为 Flutter 中的链接?非常感谢。
【解决方案2】:

您可以使用RichTextTextSpan 的列表合并为一个文本。

    return RichText(
      text: TextSpan(
        text: 'Hello ',
        style: DefaultTextStyle.of(context).style,
        children: <TextSpan>[
          TextSpan(
              text: 'world!',
              style: TextStyle(fontWeight: FontWeight.bold)),
          TextSpan(
              text: ' click here!',
              recognizer: TapGestureRecognizer()
                ..onTap = () => print('click')),
        ],
      ),
    );

【讨论】:

  • onTap前面的两个点是什么意思?
  • @user3808307 这是级联符号 - dart.dev/guides/language/language-tour#cascade-notation-。它可以帮助您在同一个对象中进行一系列操作,因为它返回底层对象的实例。因此,在这种情况下,我们正在实现 TapGestureRecognizeronTap() 方法,但仍将其实例从 TextSpan 返回到 recognizer 属性
  • 像传播运算符?
  • 如果您在谈论 JS 扩展运算符,它适用于可迭代对象,它允许我们从数组中获取参数列表。所以不,这些是不同的东西。
  • 我有一个从数据库中获取的字符串,例如nice concept of help/support - https://support.google.com/firebase?authuser=0#topic=6399725 现在告诉我如何将这个 URL 从这个字符串转换为 Flutter 中的链接?非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-01
  • 1970-01-01
  • 2020-11-29
  • 2016-10-20
相关资源
最近更新 更多