Is there a way to detect which word in the TextSpan
was touched by the user?
This paragraph is here to get round the stack overflow robot that is insisting that I write more stuff :)
Putra Ardiansyah
You can improve by yourself
import 'package:flutter/gestures.dart';
...
new RichText(
text: new TextSpan(text: 'Non touchable. ', children: [
new TextSpan(
text: 'Tap here.',
recognizer: new TapGestureRecognizer()..onTap = () => print('Tap Here onTap'),
)
]),
);
You can use recognizer
property of TextSpan
which allows almost every type of event. Here is a basic implementation.
import 'package:flutter/gestures.dart';
//... Following goes in StatefulWidget subclass
TapGestureRecognizer _recognizer1;
DoubleTapGestureRecognizer _recognizer2;
LongPressGestureRecognizer _recognizer3;
@override
void initState() {
super.initState();
_recognizer1 = TapGestureRecognizer()
..onTap = () {
print("tapped");
};
_recognizer2 = DoubleTapGestureRecognizer()
..onDoubleTap = () {
print("double tapped");
};
_recognizer3 = LongPressGestureRecognizer()
..onLongPress = () {
print("long pressed");
};
}
@override
Widget build(BuildContext context) {
var underlineStyle = TextStyle(decoration: TextDecoration.underline, color: Colors.black, fontSize: 16);
return Scaffold(
appBar: AppBar(title: Text("TextSpan")),
body: RichText(
text: TextSpan(
text: 'This is going to be a text which has ',
style: underlineStyle.copyWith(decoration: TextDecoration.none),
children: <TextSpan>[
TextSpan(text: 'single tap ', style: underlineStyle, recognizer: _recognizer1),
TextSpan(text: 'along with '),
TextSpan(text: 'double tap ', style: underlineStyle, recognizer: _recognizer2),
TextSpan(text: 'and '),
TextSpan(text: 'long press', style: underlineStyle, recognizer: _recognizer3),
],
),
),
);
}
来源:https://stackoverflow.com/questions/48914775/gesture-detection-in-flutter-textspan