有没有办法检测用户触摸 TextSpan
中的哪个单词?
这段文字只是为了绕过 Stack Overflow 的机器人,它坚持让我写更多的东西 :)
你可以自行改进
import 'package:flutter/gestures.dart';
...
RichText(
text: TextSpan(text: 'Non touchable. ', children: [
TextSpan(
text: 'Tap here.',
recognizer: TapGestureRecognizer()..onTap = () => print('Tap Here onTap'),
)
]),
);
屏幕截图:
使用TextSpan
的recognizer
属性,该属性允许几乎所有类型的事件。
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.
},
),
],
),
)
遍历字符串以获得字符串数组,为每个创建单独的文本并添加手势识别器
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,
),
TapGestureRecognizer
的dispose()
方法怎么样?这是必要的吗? - Alex Semeniuk