如何向 TextSpan 添加多个手势识别器?

2024-02-25

我想将 TapGestureRecognizer 和 LongPressGestureRecognizer 添加到TextSpan https://api.flutter.dev/flutter/painting/TextSpan-class.html。现在我可以添加其中之一,但不能同时添加两者。

我研究了 GestureDetector 类,并想用它来包装 TextSpan,但 RichText 元素只接受 TextSpan,而不接受 Widget。

这就是我现在所拥有的:

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

我想补充一下..onLongPress该代码中的某处。

最后,两个手势都应该在单个文本范围内起作用。


似乎不可能向 TextSpan 添加多个 GestureRecognizer,但这里有一种针对您的情况的解决方法,仅使用 TapGestureRecognizer 并使用 onTapUp 和 onTapDown 来检测点击并使用计时器模拟长按:

TapGestureRecognizer _tapGestureRecognizer;
Timer _timer;

@override
void initState() {
  super.initState();
  _initRecognizer();
}

_initRecognizer() {
  _tapGestureRecognizer = TapGestureRecognizer();
  _tapGestureRecognizer.onTapUp = (_) {
    if (_timer != null && _timer.isActive) {
      print('Tap');
      _timer.cancel();
    }
  };
  _tapGestureRecognizer.onTapDown = (_) {
    _timer = Timer(Duration(seconds: 1), () {
      print('Long Tap');
    });
  };
}

@override
void dispose() {
  if (_timer != null) {
    _timer.cancel();
    _timer = null;
  }
  super.dispose();
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    backgroundColor: Colors.grey,
    appBar: AppBar(),
    body: Padding(
      padding: EdgeInsets.all(16.0),
      child: RichText(
        text: TextSpan(
          children: [
            TextSpan(
              text: "This is some text.",
              recognizer: _tapGestureRecognizer,
              style: Theme.of(context).textTheme.title,
            ),
            TextSpan(
              text:
              "Another piece of text. Another piece of text. Another piece of text. Another piece of text.",
              style: Theme.of(context).textTheme.title,
            ),
          ],
        ),
      ),
    ),
  );
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何向 TextSpan 添加多个手势识别器? 的相关文章

随机推荐