skip to Main Content

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, …).

2

Answers


  1. Chosen as BEST ANSWER

    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,
                    ),
                ),
            ),
        ),
    )
    

  2. 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,
              ),
            ),
          ),
        ],
      ),
    ),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search