tomwyr
tomwyr

Reputation: 1412

Handle tap event in parent widget

In my app tree I have two widgets:

GestureDetector(
   onTap: () => print('Outer'),
   child: IconButton(
     icon: Icon(Icons.add),
     onPressed: () => print('Inner')),
   ),
)

Both of them are trying to react to touch event but only child's callback is invoked (which is default behaviour). Is it possible to define widgets in a way that will prevent ancestor from propagating touch event to its children? Or maybe the only way is to implement such behaviour on your own, e.g. by making use of GestureArena?

Upvotes: 4

Views: 3099

Answers (1)

Romain Rastel
Romain Rastel

Reputation: 5612

I think you are looking for the AbsorbPointer widget:

A widget that absorbs pointers during hit testing.

When absorbing is true, this widget prevents its subtree from receiving pointer events by terminating hit testing at itself. It still consumes space during layout and paints its child as usual. It just prevents its children from being the target of located events, because it returns true from RenderBox.hitTest.

You can use it like this:

GestureDetector(
  onTap: () => print('Outer'),
  child: AbsorbPointer(
    child: IconButton(
      icon: Icon(Icons.add),
      onPressed: () => print('Inner'),
    ),
  ),
),

Upvotes: 13

Related Questions