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 text which is pressable or clickable. In this Flutter tutorial, let’s check how to make text clickable.

I am using the 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(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key});

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

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

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

Similar Posts

Leave a Reply