Flutter中的手势检测TextSpan

117

有没有办法检测用户触摸 TextSpan 中的哪个单词?

这段文字只是为了绕过 Stack Overflow 的机器人,它坚持让我写更多的东西 :)

5个回答

215

你可以自行改进

import 'package:flutter/gestures.dart';
...

RichText(
      text: TextSpan(text: 'Non touchable. ', children: [
        TextSpan(
          text: 'Tap here.',
          recognizer: TapGestureRecognizer()..onTap = () => print('Tap Here onTap'),
        )
      ]),
    );

1
谢谢,我忘记导入'gestures.dart'包了; 使用import 'package:flutter/gestures.dart';后,它对我起作用了。 - MUHAMMED IQBAL PA
1
请记住,触发事件仅对“text”有效,而不适用于“children”中提供的任何TextSpan。 - surenyonjan
11
为什么你使用“..”而不是“。”? - Sachintha Udara
3
你如何测试这个功能?如果它是一个包含多个TextSpan的RichText,且其中一个TextSpan可以点击,你在测试期间如何模拟点击操作? - lawonga
7
调用 TapGestureRecognizerdispose() 方法怎么样?这是必要的吗? - Alex Semeniuk
你知道如何同时实现onTap和onLongPressed吗?非常感谢。 - Quang Khải Đàm

100

屏幕截图:

输入图像描述


使用TextSpanrecognizer属性,该属性允许几乎所有类型的事件。

RichText(
  text: TextSpan(
    children: [
      TextSpan(
        text: 'Single tap',
        style: TextStyle(color: Colors.red[300]),
        recognizer: TapGestureRecognizer()..onTap = () {
          // Single tapped.
        },
      ),
      TextSpan(
        text: ' Double tap',
        style: TextStyle(color: Colors.green[300]),
        recognizer:  DoubleTapGestureRecognizer()..onDoubleTap = () {
          // Double tapped.
        }
      ),
      TextSpan(
        text: ' Long press',
        style: TextStyle(color: Colors.blue[300]),
        recognizer: LongPressGestureRecognizer()..onLongPress = () {
          // Long Pressed.
        },
      ),
    ],
  ),
)


你如何将下划线文本传递给处理轻拍的方法? - Alex Semeniuk
1
我建议您将文本放入一个变量中,然后可以在触摸处理闭包中使用它。@AlexSemeniuk - jlyonsmith
@jlyonsmith 是的,我最終做了這個:創建一個將識別器與其值鏈接起來並在路徑中填充它的地圖。想不出更好的解決方案。 - Alex Semeniuk

10

遍历字符串以获得字符串数组,为每个创建单独的文本并添加手势识别器

 List<TextSpan> createTextSpans(){
    final string = """Text seems like it should be so simple, but it really isn't.""";
    final arrayStrings = string.split(" ");
    List<TextSpan> arrayOfTextSpan = [];
    for (int index = 0; index < arrayStrings.length; index++){
      final text = arrayStrings[index] + " ";
      final span = TextSpan(
        text: text,
        recognizer: TapGestureRecognizer()..onTap = () => print("The word touched is $text")
      );
      arrayOfTextSpan.add(span);
    }
    return arrayOfTextSpan;

1
为什么要写这个双点呢? - Alan Donizete
1
你可以在这里阅读更多关于它的内容。 - abubz

2
late TapGestureRecognizer tapGestureRecognizer;

@override
    void initState() {
      super.initState();
    
      tapGestureRecognizer = TapGestureRecognizer()
        ..onTap = () {
          widget.onProfileDetails();
        };
    }
    
    @override
    void dispose() {
      super.dispose();
      tapGestureRecognizer.dispose();
    }
    
    @override
    Widget build(BuildContext context) {
      return Flexible(
        child: RichText(
          text: TextSpan(
            children: [
              TextSpan(
                text: widget.notificationObject.name,
                style: TextStyle(
                  fontSize: width * 0.044,
                  fontFamily: 'HelveticaNeueRegular',
                  color: Theme.of(context).primaryColor,
                ),
                recognizer: tapGestureRecognizer,
              ),
            ],
          ),
        ),
      );
    }

1
 RichText(
                text: TextSpan(
                  text: "If you don't have a account ",
                  style: TextStyle(
                    fontFamily: AppFonts.phagsPa,
                    fontSize: 16,
                    color: AppColors.white,
                  ),
                  children: [
                    TextSpan(
                      text: "sign-up".toUpperCase(),
                      style: TextStyle(
                        color: AppColors.btnBgColor,
                        fontWeight: FontWeight.bold,
                      ),
                      recognizer: TapGestureRecognizer()
                        ..onTap = () {
                          Get.to(() => MerchantSignupPage());
                        },
                    ),
                    TextSpan(text: " here")
                  ],
                ),
                textAlign: TextAlign.center,
              ),

以上解决方案出现错误:缺少选择器,例如'.identifier'或'[0]'。尝试添加一个选择器。 - user21172488
以上解决方案出现错误:缺少选择器,如'.identifier'或'[0]'。请尝试添加一个选择器。 - user21172488

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