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

时间:2019-10-11 14:05:38

标签: flutter

我想将TapGestureRecognizer和LongPressGestureRecognizer都添加到TextSpan中。现在,我可以添加一个,但不能两个都添加。

我已经研究了GestureDetector类,并希望用它包装TextSpan,但是RichText元素仅接受TextSpans,而不接受小部件。

这就是我现在拥有的:

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

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

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

2 个答案:

答案 0 :(得分:1)

似乎不可能在一个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,
            ),
          ],
        ),
      ),
    ),
  );
}

答案 1 :(得分:0)

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

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