Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add multiple gesture recognizers to TextSpan?

Tags:

flutter

I'd like to add both a TapGestureRecognizer and a LongPressGestureRecognizer to a TextSpan. Right now I can add either one, but not both.

I've looked into the GestureDetector class and wanted to wrap TextSpan with it, but the RichText element only accepts TextSpans and not Widgets.

This is what I have now:

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

And I want to add ..onLongPress somewhere in that code.

At the end both gestures should work on the single text span.

like image 637
user213294 Avatar asked Jan 01 '23 14:01

user213294


1 Answers

It doesn't seem to be possible to add more than one GestureRecognizer to a TextSpan, but here is a workaround for your case with just the TapGestureRecognizer and using the onTapUp and onTapDown to detect a tap and to simulate a long tap, using a Timer:

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,
            ),
          ],
        ),
      ),
    ),
  );
}
like image 82
Pablo Barrera Avatar answered Feb 06 '23 05:02

Pablo Barrera