Reputation: 120539
Assume I have some Flutter code like this:
// ...
body: new Center(
child: new Text(
'Hello, I am some text',
),
),
// ...
How can I make the Text on the screen respond to a tap? (For example, simply printing to the log when I tap the text.)
Thanks!
Upvotes: 33
Views: 57782
Reputation: 257
You can use these aproaches
Upvotes: 0
Reputation: 1142
you can use Rich text for tappable text:-
Divide the text in Text Span accordingly and use Tap Gesture in that text you want to make tappable.
TapGestureRecognizer _termsConditionRecognizer;
TapGestureRecognizer _privacyPolicyRecognizer;
@override
void dispose() {
_privacyPolicy.dispose();
_termsCondition.dispose();
super.dispose();
}
@override
void initState() {
super.initState();
_termsConditionRecognizer = TapGestureRecognizer()
..onTap = () {
print("Terms and condition tapped");
};
_privacyPolicyRecognizer = TapGestureRecognizer()
..onTap = () {
print("Provacy Policy tapped");
};
}
@override
Widget build(BuildContext context) {
return Container(
child: Center(
child: RichText(
text: TextSpan(
text: 'By signing up you agree to the ',
children: [
TextSpan(
text: 'Terms And Condition',
recognizer: _termsConditionRecognizer,
),
TextSpan(
text: ' and ',
),
TextSpan(
text: 'Privacy Policy',
recognizer: _privacyPolicyRecognizer,
),
],
),
),
),
);
}
Upvotes: 19
Reputation: 7742
As seen on this answer, you can use an InkWell or a gesture detector.
For example
InkWell(
child: Text("Hello"),
onTap: () {print("value of your text");},
)
Or
var textValue = "Flutter"
InkWell(
child: Text(textValue),
onTap: () {print(textValue);},
)
EDIT : As Collin Jackson suggested, you can also use a FlatButton
FlatButton(
onPressed: () {print("Hello world");},
child: Text("Hello world"),
);
If you don't need or require material (FlatButton, InkWell, etc), you can use GestureDetector:
GestureDetector(
onTap: () { print("I was tapped!"); },
child: Text("Hello world"),
)
Upvotes: 89
Reputation: 37969
One more approach
Create the function that returns tapable widget:
Widget tapableText(String text, Function onTap) {
return GestureDetector(
onTap: onTap,
child: Text(text),
);
}
Usage example:
...
child: tapableText('Hello', () { print('I have been tapped :)'); }),
...
Upvotes: 3
Reputation: 1121
You can also make the text appear in the form of a URL like so:
new FlatButton(
onPressed: () {print("You've tapped me!")},
child: Text(
"Tap me!",
style: TextStyle(color: Colors.blue, decoration: TextDecoration.underline)),
);
Upvotes: 3