Gesture detection in Flutter TextSpan

你离开我真会死。 提交于 2019-11-30 01:53:01

问题


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 :)


回答1:


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



回答2:


You can use recognizer property of TextSpan which allows almost every type of event. Here is a basic implementation.

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



来源:https://stackoverflow.com/questions/48914775/gesture-detection-in-flutter-textspan

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!