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.
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,
),
],
),
),
),
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With