How to put mouse cursor on hyper text in TextSpan in Flutter web

Viewed 1350

I am using something like this to have links in text inside a paragraph

RichText(
  text: TextSpan(
    children: [
      TextSpan(text: 'This is a going to be a Text which has '),
      TextSpan(
        text: 'single tap',
        style: style,
        recognizer: TapGestureRecognizer()
          ..onTap = () {
            // single tapped
          },
      ),
    ],
  ),
)

Now, it works fine, but I cannot have a hand cursor when rolling over the text?

I was looking on how to do it and found this

MouseRegion(
  cursor: SystemMouseCursors.click,
  child: Container(
      height: 30,
      width: 30,
      color: Colors.red,
  ),
),

but is not possible to wrap one of the TextSpans in a Container and MouseRegion.

2 Answers

You can create a custom WidgetSpan like this:

class MouseRegionSpan extends WidgetSpan {
  MouseRegionSpan({
    @required MouseCursor mouseCursor,
    @required InlineSpan inlineSpan,
  }) : super(
          child: MouseRegion(
            cursor: mouseCursor,
            child: Text.rich(
              inlineSpan,
            ),
          ),
        );
}

and wrap your TextSpan with it:

MouseRegionSpan(
  mouseCursor: SystemMouseCursors.click,
  inlineSpan: TextSpan(
    text: 'single tap',
    style: style,
    recognizer: TapGestureRecognizer()
      ..onTap = () {
        // single tapped
      },
  ),
),

Recently, this feature has been added to TextSpans.

As of Flutter 5647407 on master (probably going to be in the 2.1.0 release), the mouse cursor is clickable (hand cursor) by default. So you do not need to take any action other than upgrading Flutter.

Manually specifying

You can manually specify the mouseCursor property:

TextSpan(
  text: 'single tap',
  style: style,
  mouseCursor: MaterialStateMouseCursor.clickable,
  recognizer: TapGestureRecognizer()
    ..onTap = () {
      // single tapped
    },
),

Furthermore, there are now onEnter and onExit callbacks for responding to the mouse entering and leaving the text span.

Default SystemMouseCursors.click

If you take a look at the commit, you will notice that the default is now SystemMouseCursors.click when you specify a recognizer.

Related