Search code examples
fluttertooltiprichtexttextspan

Flutter: How to display Tooltip for TextSpan inside RichText


I have big paragraph, and many words have to have tooltip message. When you click on any of these words, then tooltip message should be appeared.

I tried to use RichText widget where it contains many TextSpan children like below:

RichText(
  text: TextSpan(
     children: <TextSpan>[
        TextSpan(text: "Welcome to"),
        TextSpan(text: "Flutter"),
        ... 
     ]),
),

I need to display tooltip text when i click on TextSpan I tried to wrap TextSpan with Tooltip widget

RichText(
  text: TextSpan(
     children: <TextSpan>[
        TextSpan(text: "Welcome to"),
        ...
        Tooltip(
            message: "any text here",
            child: TextSpan(text: "Flutter"),
        ),
        ...            
     ]),
),

but this is not possible since the children have to be TextSpan only.

anyone have an idea on how to achieve this requirement?


Solution

  • With TextSpan you have 2 ways to do it: With or without using children parameter.

    Widget _toolTipSimple() {
        return Center(
          child: Tooltip(
            message: "Flutter",
            child: RichText(
              text: TextSpan(
                  text: "Welcome to", style: TextStyle(fontSize: 70)),
            ),
          ),
       );
    }
    

    This one is a complex version without a Tooltip but it handles the click on a specific word:

    Widget _snackBarTextSpanChildren(BuildContext context) {
        return Center(
          child: RichText(
            textAlign: TextAlign.center,
            text: TextSpan(
              children: [
                TextSpan(text: "Welcome to ", style: TextStyle(fontSize: 70)),
                TextSpan(
                    text: "Flutter",
                    style: TextStyle(fontSize: 70),
                    recognizer: TapGestureRecognizer()..onTap = () {
                      Scaffold.of(context).showSnackBar(SnackBar(content: Text('Hello!')));
                    }),
              ],
            ),
          ),
        );
      }
    

    The result for this one is the following:

    Snackbar on specific word