如何在Flutter中使文本可点击(响应点击)?

30
假设我有一些Flutter代码,如下所示:
  // ...
  body: new Center(
    child: new Text(
      'Hello, I am some text',
    ),
  ),
  // ...

如何使屏幕上的文本响应轻拍?(例如,当我轻拍文本时,简单地打印到日志中。)

谢谢!

5个回答

86

正如这个回答所示,你可以使用 InkWell 或 Gesture Detector。

例如

InkWell(
    child: Text("Hello"),
    onTap: () {print("value of your text");},
)

或者

var textValue = "Flutter"
InkWell(
    child: Text(textValue),
    onTap: () {print(textValue);},
)

编辑:如Collin Jackson建议的那样,您也可以使用FlatButton。

FlatButton(
  onPressed: () {print("Hello world");},
  child: Text("Hello world"),
);

如果您不需要或不需要材料(FlatButton,InkWell等),可以使用GestureDetector

GestureDetector(
  onTap: () { print("I was tapped!"); },
  child: Text("Hello world"),
)

有没有一种通过填充或其他类似方法来增加文本上下方的选项卡区域的方式? - Bishoy Hanna
1
FlatButton已弃用,请使用TextButton。 - dqualias

17

您可以使用富文本来创建可点击的文本:

根据需要,将文本分割成文本段落,并在要创建为可点击的文本中使用 Tap Gesture。

  TapGestureRecognizer _termsConditionRecognizer;
  TapGestureRecognizer _privacyPolicyRecognizer;

  @override
  void dispose() {
    _privacyPolicy.dispose();
    _termsCondition.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _termsConditionRecognizer = TapGestureRecognizer()
      ..onTap = () {
        print("Terms and condition tapped");
      };
    _privacyPolicyRecognizer = TapGestureRecognizer()
      ..onTap = () {
        print("Provacy Policy tapped");
      };
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
        child: RichText(
          text: TextSpan(
            text: 'By signing up you agree to the ',
            children: [
              TextSpan(
                text: 'Terms And Condition',
                recognizer: _termsConditionRecognizer,
              ),
              TextSpan(
                text: ' and ',
              ),
              TextSpan(
                text: 'Privacy Policy',
                recognizer: _privacyPolicyRecognizer,
              ),
            ],
          ),
        ),
      ),
    );
  }

请尝试解释答案而不是直接给出代码片段。这可能有助于社区。 - Kiran Maniya

3

另一种方法

创建一个返回可点击小部件的函数:

Widget tapableText(String text, Function onTap) {
  return GestureDetector(
    onTap: onTap,
    child: Text(text),
  );
}

使用示例:

...
child: tapableText('Hello', () { print('I have been tapped :)'); }),
...

3
您还可以将文本以URL的形式显示,如下所示:

new FlatButton(
  onPressed: () {print("You've tapped me!")},
  child: Text(
    "Tap me!", 
    style: TextStyle(color: Colors.blue, decoration: TextDecoration.underline)),
);

0

你可以使用以下方法:

  1. 使用TextButton并提供文本信息。
  2. 使用FlatButton并提供文本信息,为了去除额外的填充,你可以使用materialTapTargetSize属性,并提供MaterialTapTargetSize.shrinkWrap。然而在新版本中,FlatButton已经过时。
  3. 如上所述,使用InkWell。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接