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 :)
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 :)
You can improve by yourself
import 'package:flutter/gestures.dart';
...
RichText(
text: TextSpan(text: 'Non touchable. ', children: [
TextSpan(
text: 'Tap here.',
recognizer: TapGestureRecognizer()..onTap = () => print('Tap Here onTap'),
)
]),
);
Screenshot:
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,
),
],
),
),
);
}
RichText(
text: TextSpan(
text: "If you don't have a account ",
style: TextStyle(
fontFamily: AppFonts.phagsPa,
fontSize: 16,
color: AppColors.white,
),
children: [
TextSpan(
text: "sign-up".toUpperCase(),
style: TextStyle(
color: AppColors.btnBgColor,
fontWeight: FontWeight.bold,
),
recognizer: TapGestureRecognizer()
..onTap = () {
Get.to(() => MerchantSignupPage());
},
),
TextSpan(text: " here")
],
),
textAlign: TextAlign.center,
),