使文本的特定部分在 flutter 中可点击[重复]

问题描述 投票:0回答:2

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

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

text flutter dart clickable
2个回答
225
投票
import 'package:flutter/gestures.dart';

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"');
                }),
        ],
      ),
    );
  }


35
投票

您可以使用

RichText
TextSpan
列表合并到单个文本中。

    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')),
        ],
      ),
    );
© www.soinside.com 2019 - 2024. All rights reserved.