Flutter TextSpan中的手势检测

adk*_*dko 14 gesture flutter

有没有办法检测用户触摸TextSpan中的哪个单词?

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

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)

  • 为什么用“..”而不是“.” ? (5认同)
  • 调用 `TapGestureRecognizer` 的 `dispose()` 方法怎么样?有必要吗? (5认同)
  • 您将如何测试?如果它是带有多个TextSpan的RichText,并且其中一个是可点击的TextSpan,那么在测试期间如何点击它? (2认同)

小智 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)


Cop*_*oad 5

您可以使用允许几乎所有类型的事件的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)

在此处输入图片说明