recognizer property Null safety

GestureRecognizer? recognizer
final

A gesture recognizer that will receive events that hit this span.

InlineSpan itself does not implement hit testing or event dispatch. The object that manages the InlineSpan painting is also responsible for dispatching events. In the rendering library, that is the RenderParagraph object, which corresponds to the RichText widget in the widgets layer; these objects do not bubble events in InlineSpans, so a recognizer is only effective for events that directly hit the text of that InlineSpan, not any of its children.

InlineSpan also does not manage the lifetime of the gesture recognizer. The code that owns the GestureRecognizer object must call GestureRecognizer.dispose when the InlineSpan object is no longer used.

This example shows how to manage the lifetime of a gesture recognizer provided to an InlineSpan object. It defines a BuzzingText widget which uses the HapticFeedback class to vibrate the device when the user long-presses the "find the" span, which is underlined in wavy green. The hit-testing is handled by the RichText widget. It also changes the hovering mouse cursor to precise.
class BuzzingText extends StatefulWidget {
  const BuzzingText({super.key});

  @override
  State<BuzzingText> createState() => _BuzzingTextState();
}

class _BuzzingTextState extends State<BuzzingText> {
  late LongPressGestureRecognizer _longPressRecognizer;

  @override
  void initState() {
    super.initState();
    _longPressRecognizer = LongPressGestureRecognizer()
      ..onLongPress = _handlePress;
  }

  @override
  void dispose() {
    _longPressRecognizer.dispose();
    super.dispose();
  }

  void _handlePress() {
    HapticFeedback.vibrate();
  }

  @override
  Widget build(BuildContext context) {
    return Text.rich(
      TextSpan(
        text: 'Can you ',
        style: const TextStyle(color: Colors.black),
        children: <InlineSpan>[
          TextSpan(
            text: 'find the',
            style: const TextStyle(
              color: Colors.green,
              decoration: TextDecoration.underline,
              decorationStyle: TextDecorationStyle.wavy,
            ),
            recognizer: _longPressRecognizer,
            mouseCursor: SystemMouseCursors.precise,
          ),
          const TextSpan(
            text: ' secret?',
          ),
        ],
      ),
    );
  }
}

Implementation

final GestureRecognizer? recognizer;