How to Make Text Clickable in Flutter

Usually, a text doesn’t have any click events. But there are cases, such as hyperlinks, where we need a text which is pressable or clickable. In this Flutter tutorial, let’s check how to make text clickable.

I am using RichText widget for this example. It helps us to make a specific text clickable. The TextSpan class has a property named recognizer and you can apply your gesture recognizer there.

Following is the complete Flutter example where a specific text can be clicked.

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Make Text Clickable',
      home: FlutterExample(),
    );
  }
}

class FlutterExample extends StatelessWidget {
  const FlutterExample({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('Flutter Clickable Text Example')),
        body: Center(
            child: RichText(
          text: TextSpan(
            text: 'Here is the ',
            style: TextStyle(fontSize: 30, color: Colors.black),
            children: <TextSpan>[
              TextSpan(
                  text: 'clickable ',
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      print('The button is clicked!');
                    },
                  style: TextStyle(
                    color: Colors.blue,
                  )),
              TextSpan(text: 'text!'),
            ],
          ),
        )));
  }
}

Here, the text clickable can be clicked and it print the given output.

That’s how you make specific text clickable in Flutter easily.

Leave a Comment

Your email address will not be published. Required fields are marked *