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
}),
],
),
);
}
}
You can use Text.rich, a const text widget, as an alternative to RichText. It integrates with the default text style automatically. In this article, we went over the RichText widget and the TextSpan widget and a few examples of using them in Flutter applications.
We will see how to implement a demo program of the selectable text widget and show you how to utilize that widget to copy/select the text, making a text selectable is really simple in Flutter, you simply need to utilize the SelectableText widget in your flutter applications. A run of selectable text with a single style.
The inner widgets need to have their own TextStyle for overriding the default style. In the first example, there are three inner TextSpan widgets. The first one sets the font color to blue. The second doesn't have any styling, so it completely uses the outer TextSpan 's style. The last one uses underline decoration.
As the name suggests, RichText provides more options to the way a text is displayed on the screen. The style property of text widget is used to apply various styles to a text, but a limitation of it is, the style gets applied to the entire text irrespective of whether the text is a single line or multiline.
This issue has been fixed. I tried running your snippet and verified it to be working on Flutter 2.2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With