Osama Na
Osama Na

Reputation: 277

Flutter: Enable text selection with clickable TextSpan inside RichText

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
                }),
        ],
      ),
    );
  }
}

Upvotes: 12

Views: 7875

Answers (1)

Omatt
Omatt

Reputation: 10453

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

Upvotes: 5

Related Questions