How to Make Container Clickable in Flutter

In normal cases, the Container widget doesn’t respond to touches. Sometimes, we may need to create custom widgets which are clickable. Let’s see how to make container widget clickable widget in Flutter.

The GestureDetector widget is used to detect gestures. Hence, we use GestureDetector in this example so that we can detect taps on the container. All you need is to wrap the Container widget with the GestureDetector as given below.

import 'package:flutter/material.dart';

class ClickableContainerExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Tutorials',
      home: Main()
    );
  }
}

/// This is the stateless widget that the main application instantiates.
class Main extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Clickable Container Example'),
      ),
      body: Builder(
        builder: (context) => Center(child:// The GestureDetector wraps the button.
GestureDetector(
  // When the child is tapped, show a snackbar.
  onTap: () {
    final snackBar = SnackBar(content: Text("Clicked the Container!"));

    Scaffold.of(context).showSnackBar(snackBar);
  },
  // The custom button
  child: Container(
    padding: EdgeInsets.all(12.0),
    decoration: BoxDecoration(
      color: Theme.of(context).buttonColor,
    ),
    child: Text('My Button'),
  ),
),
        ),
      ),
    );
  }
}

In the above Flutter example, when the container with the text ‘My Button’ is pressed we detects the tap and show the snackbar. Check the output of the example below.

Enable click flutter example

I hope this Flutter tutorial will help you!

2 thoughts on “How to Make Container Clickable in Flutter”

Leave a Comment

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