颤振文本跨度中的手势检测

有没有一种方法来检测哪个字在 TextSpan被用户触摸?

这一段是为了避免堆栈溢出机器人坚持要我写更多的东西:)

65529 次浏览

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'),
)
]),
);

Screenshot:

enter image description here


Use recognizer property of TextSpan which allows almost all types of event.

RichText(
text: TextSpan(
children: [
TextSpan(
text: 'Single tap',
style: TextStyle(color: Colors.red[300]),
recognizer: TapGestureRecognizer()..onTap = () {
// Single tapped.
},
),
TextSpan(
text: ' Double tap',
style: TextStyle(color: Colors.green[300]),
recognizer:  DoubleTapGestureRecognizer()..onDoubleTap = () {
// Double tapped.
}
),
TextSpan(
text: ' Long press',
style: TextStyle(color: Colors.blue[300]),
recognizer: LongPressGestureRecognizer()..onLongPress = () {
// Long Pressed.
},
),
],
),
)


Iterate over the string to get an array of strings, create separate text span for each and add the gesture recognizer

 List<TextSpan> createTextSpans(){
final string = """Text seems like it should be so simple, but it really isn't.""";
final arrayStrings = string.split(" ");
List<TextSpan> arrayOfTextSpan = [];
for (int index = 0; index < arrayStrings.length; index++){
final text = arrayStrings[index] + " ";
final span = TextSpan(
text: text,
recognizer: TapGestureRecognizer()..onTap = () => print("The word touched is $text")
);
arrayOfTextSpan.add(span);
}
return arrayOfTextSpan;
late TapGestureRecognizer tapGestureRecognizer;


@override
void initState() {
super.initState();
    

tapGestureRecognizer = TapGestureRecognizer()
..onTap = () {
widget.onProfileDetails();
};
}
    

@override
void dispose() {
super.dispose();
tapGestureRecognizer.dispose();
}
    

@override
Widget build(BuildContext context) {
return Flexible(
child: RichText(
text: TextSpan(
children: [
TextSpan(
text: widget.notificationObject.name,
style: TextStyle(
fontSize: width * 0.044,
fontFamily: 'HelveticaNeueRegular',
color: Theme.of(context).primaryColor,
),
recognizer: tapGestureRecognizer,
),
],
),
),
);
}