我想将 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/