Put*_*yah 29
你可以自己改进
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'),
)
]),
);
Run Code Online (Sandbox Code Playgroud)
小智 6
遍历字符串以获取字符串数组,为每个字符串创建单独的文本跨度并添加手势识别器
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;
Run Code Online (Sandbox Code Playgroud)
您可以使用允许几乎所有类型的事件的recognizer属性TextSpan。这是一个基本的实现。
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),
],
),
),
);
}
Run Code Online (Sandbox Code Playgroud)