Flutter: Enable text selection with clickable TextSpan inside RichText

3,120

This issue has been fixed. I tried running your snippet and verified it to be working on Flutter 2.2

Share:
3,120
Osama Na
Author by

Osama Na

Updated on December 02, 2022

Comments

  • Osama Na
    Osama Na over 1 year

    I have a requirement to enable text selection within RichText. Also i need to call some code when user click on specific TextSpan.

    I tired to run below code. But i notice that onTap is working only with _nonSelectableRichText(), while it is not working with _selectableRichText.

    I don’t know if that is a bug or not… but I am asking if anyone has a solution that combines these two features?

    import 'package:flutter/gestures.dart';
    import 'package:flutter/material.dart';
    
    class TestPage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: Builder(
              builder: (context) => Container(
                child: _nonSelectionRichText(context),
                //child: _selectionRichText(context),
              ),
            ),
          ),
        );
      }
    
      Widget _nonSelectableRichText(BuildContext context) {
        return RichText(
          text: TextSpan(
            children: [
              TextSpan(
                  text: "Welcome to ",
                  style: TextStyle(color: Colors.black, fontSize: 70)),
              TextSpan(
                  text: "Flutter",
                  style: TextStyle(color: Colors.black, fontSize: 70),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      print("Flutter"); // will work here
                    }),
            ],
          ),
        );
      }
    
      Widget _selectableRichText(BuildContext context) {
        return SelectableText.rich(
          TextSpan(
            children: [
              TextSpan(
                  text: "Welcome to ",
                  style: TextStyle(color: Colors.black, fontSize: 70)),
              TextSpan(
                  text: "Flutter",
                  style: TextStyle(color: Colors.black, fontSize: 70),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      print("Flutter"); // will not work here
                    }),
            ],
          ),
        );
      }
    }