首页 > 解决方案 > 如何向 TextSpan 添加多个手势识别器?

问题描述

我想将 TapGestureRecognizer 和 LongPressGestureRecognizer 添加到TextSpan。现在我可以添加任何一个,但不能同时添加。

我查看了 GestureDetector 类并想用它包装 TextSpan,但 RichText 元素只接受 TextSpan 而不是小部件。

这就是我现在所拥有的:

TextSpan(
    text: "some text",
    recognizer: TapGestureRecognizer()
    ..onTap = () { print('tapped'); }
)

我想..onLongPress在该代码中添加某处。

最后,两个手势都应该在单个文本跨度上工作。

标签: flutter

解决方案


您可以使用WidgetSpan设置您的跨度并通过 GestureDetector 检测 TapGestureRecognizer 和 LongPressGestureRecognizer

 TextSpan(
          children: <InlineSpan>[
            TextSpan(text: 'Flutter is'),
            WidgetSpan(
                child: GestureDetector(
                  onTap: () {
                    
                  },
                  onLongPress: () {
                    
                  },
                  child: Text(' Hello World! '),
                )
            ),
            TextSpan(text: 'the best!'),
          ],
        )

推荐阅读