Parlor311
Parlor311

Reputation: 29

Receive press events from only the first widget under GestureDetector in Flutter

My app has a similar widget tree to what's below. onTap is called when any of the containers are tapped.

How can I make it run only when the first container (the one with the red background) is tapped?

GestureDetector(
    onTap: () => print('pressed'),
    child: Container(
        padding: const EdgeInsets.all(10),
        color: Colors.red,
        child: Container(
            padding: const EdgeInsets.all(10),
            color: Colors.green,
            child: Container(
                height: 50,
                color: Colors.blue,
            ),
        ),
    ),
),

I tried IgnorePointer and AbsorbPointer but they only work on widgets that handle pointer events (buttons, scrollables, GestureDetector, ...).

Upvotes: 3

Views: 72

Answers (2)

Parlor311
Parlor311

Reputation: 29

Not sure if this has any unwanted side effects, but it seems to work.

GestureDetector(
    onTap: () => print('pressed 1'),
    child: Container(
        padding: const EdgeInsets.all(10),
        color: Colors.red,
        child: GestureDetector(
            onTap: () { },
            child: Container(
                padding: const EdgeInsets.all(10),
                color: Colors.green,
                child: Container(
                    height: 50,
                    color: Colors.blue,
                ),
            ),
        ),
    ),
)

Upvotes: 0

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63569

You can use Stack,

SizedBox(
  height: 50 + 10 * 2,
  child: Stack(
    children: [
      Positioned.fill(
        child: GestureDetector(
          onTap: () => print('pressed'),
          child: Container(
            padding: const EdgeInsets.all(10),
            color: Colors.red,
          ),
        ),
      ),
      Positioned( //this part will render on top while it is last child,
        top: 10,
        bottom: 10,
        right: 10,
        left: 10,
        child: Container(
          padding: const EdgeInsets.all(10),
          color: Colors.green,
          child: Container(
            height: 50,
            color: Colors.blue,
          ),
        ),
      ),
    ],
  ),
),

Upvotes: 1

Related Questions