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

标签 flutter

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

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

这就是我现在所拥有的:

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

关于flutter - 如何向 TextSpan 添加多个手势识别器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58342982/

相关文章:

android - 如何存储临时值?

Flutter Riverpod Future 提供商 - 需要异步和等待?

dart - 以编程方式关注 InputField 并打开键盘

listview - 为什么 GridView.builder 返回高度扩展的元素,而 ListView.Seperated 返回正常高度的元素?

flutter - 如何计算列表中双倍数据的总和?

android - Flutter Web 设备未在 Android Studio 和 VS Code 中显示

dart - Flutter:使用 SlideTransition

flutter - 如何在 table_calendar 包 flutter 中获取当前显示的月份

flutter - 使用手势动态调整位置大小和旋转 Flutter 小部件

android - Gradle 在构建 Flutter 应用程序时突然开始出错