How to Make Any Widget Clickable in Flutter

This article will guide you on how to make any widget in Flutter clickable. Although Flutter provides built-in button widgets like ElevatedButton and TextButton, sometimes you might want to make an image, a custom container, or any other widget clickable.

For this purpose, Flutter provides a widget called GestureDetector. By wrapping any widget with GestureDetector, you can make it respond to tap events.

For example, I have used GestureDetector to make the following widgets clickable:

  • Text Widget
  • Container Widget
  • Image Widget
  • Icon Widget

Simply wrap your desired widget with GestureDetector and define the onTap callback to handle the click event.

Code:

import 'package:flutter/material.dart';

class ClickableWidget extends StatefulWidget {
  const ClickableWidget({super.key});

  @override
  State<ClickableWidget> createState() => _ClickableWidgetState();
}

class _ClickableWidgetState extends State<ClickableWidget> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SizedBox(
        width: MediaQuery.of(context).size.width,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            GestureDetector(
              onTap: () {},
              child: Text(
                'CLICK HERE',
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
              ),
            ),
            SizedBox(height: 10),
            GestureDetector(
              onTap: () {},
              child: Container(
                width: 100,
                height: 50,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(12),
                  color: Colors.black,
                ),
                child: Text(
                  'CLICK',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
            SizedBox(height: 10),
            GestureDetector(
              onTap: () {},
              child: Image.asset('asset/images/flutter.jpg', scale: 5),
            ),
            SizedBox(height: 10),
            GestureDetector(onTap: () {}, child: Icon(Icons.add, size: 50)),

            SizedBox(height: 10),
            ElevatedButton(
              onPressed: () {},
              child: Text('Inbuilt Elevated Button'),
            ),
            SizedBox(height: 10),
            TextButton(onPressed: () {}, child: Text('Inbuilt Text Button')),
          ],
        ),
      ),
    );
  }
}
Dart


Output:

Leave a Comment

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

Scroll to Top