如何在Flutter中对一些文本进行tappable(响应点击)?

时间:2017-06-09 21:25:19

标签: dart flutter

假设我有一些像这样的Flutter代码:

  // ...
  body: new Center(
    child: new Text(
      'Hello, I am some text',
    ),
  ),
  // ...

如何让屏幕上的文字响应水龙头? (例如,当我点击文本时,只需打印到日志。)

谢谢!

5 个答案:

答案 0 :(得分:15)

如此answer所示,您可以使用InkWell或手势检测器。

例如

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

或者

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

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

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

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

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

答案 1 :(得分:2)

您可以使用RTF文本作为可点击文本:-

相应地在“文本跨度”中划分文本,并在要使其可点击的文本中使用“点击手势”。

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

另一种方法

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

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

用法示例:

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

答案 4 :(得分:0)

你可以使用这些方法

  1. TextButton 并向其提供您的文本。
  2. FlatButton 并提供您的文本,以删除您可以使用的额外填充 FlatButton 的 materialTapTargetSize 属性并提供 MaterialTapTargetSize.shrinkWrap 但 FlatButton 在较新版本中已贬值。
  3. InkWell 如上所述。
相关问题