Flutter Tooltip on One Tap / Hold Down

Issue

My app has several textfields and I want to have a tooltip so that users know can see the definition of each field.

I came across this answer, but it wasn’t helpful: Flutter Tooltip on One Tap. Therefore I decided to try and fix it myself.

Solution

Here is how to do it:

First add GestureDetector as child for Tooltip,

TooltipTriggerMode.manual for triggerMode.

add onTapDown, onTapUp, and onTapCancel as follows

Widget build(BuildContext context) {
    final tooltipkey = GlobalKey<TooltipState>();
    return Tooltip(
      key: tooltipkey,
      message: message,
      triggerMode: TooltipTriggerMode.manual, // make it manual
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTapDown: (_) => _onTapDown(tooltipkey), // add this
        onTapUp: (_) => _onTapUpAndCancel(tooltipkey), // add this
        onTapCancel: () => _onTapUpAndCancel(tooltipkey), // add this
        child: Icon(EvaIcons.questionMarkCircleOutline),
      ),
    );
}

and the helper functions shown inside the code above:

void _onTapDown(GlobalKey<TooltipState> tooltipkey) {
    tooltipkey.currentState?.ensureTooltipVisible();
}

void _onTapUpAndCancel(GlobalKey<TooltipState> tooltipkey) {
    tooltipkey.currentState?.deactivate();
}

Hooray, it works. Now you can hold down the icon to display the tooltip immediately instead of holding it down for a while (the default configuration of tooltip).

Answered By – Timothy Se

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.