Gesture detection in Flutter TextSpan

我怕爱的太早我们不能终老 提交于 2019-12-01 02:51:16
Putra Ardiansyah

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

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

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