Make specific parts of a text clickable in flutter [duplicate]

孤者浪人 提交于 2020-08-24 10:48:28

问题


I want to make a part of a text tapable so I can call a function on it. Also I want to have control over the style of the tapable text. In the best case I can also increase the size of the tapable area to for example 42px.

I already looked into flutter_linkify and linkify, but that's not what I want. I'm curious if there's already a package or even built into the flutter library.


回答1:


Use RichText with TextSpan and GestureRecognizer. With GestureRecognizer you can detect tap, double tap, long press and etc.

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




回答2:


You can use RichText to merge a list of TextSpan into a single Text.

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


来源:https://stackoverflow.com/questions/58145606/make-specific-parts-of-a-text-clickable-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!