Flutter: "Incorrect use of ParentDataWidget" exception when wrapping an Expanded in a GestureDetector

28 Views Asked by At

Disclaimer: I'm relatively new to Flutter, so I am not fully clear on some of the constraints related to what widget "can" go into which other widget, so this may be a simple mistake... I appreciate everyone's patience and guidance!

Hi everyone! :)

I'll start with the change that leads to the error:

GestureDetector(
  child: Expanded(
    child: Text(
      displayTime ? "Some text" : "Some other text"
      style: textStyle),
    ),
   onTap: () { // No code yet here 
   },
),

With the above code, I get the "Incorrect use of ParentDataWidget" exception, right after wrapping the Expanded in a GestureDetector. If I remove the GestureDetector, the app works fine.

The widget this sits in is in the following tree: Widget Tree of the widget where the GestureDetector sits

This Widget, itself, sits in the following tree (TaskBubble): View of where the problematic widget sits in

Now, I could always work around this and find another way to get that onTap(), but I'd rather understand the issue to fix it for good.

I've tried the following:

  1. Removing the GestureDetector - which removes the exception
  2. Removing the Expanded - and it works, but then I'm not getting the layout I want - i.e. a Text field expanding between two other widgets in a row
  3. Understanding whether my Widget tree choices are correct (i.e., roughly: ListView, Row, Widget, Row, GestureDetector, Expanded tree) - but I can't find anything conclusive at this point.

Thanks for the support!

Cheers!

1

There are 1 best solutions below

0
On

Alright, I guess that posting the question was sufficient to find a solution. A suggested article right under my question was: How to use Expanded with e.g. GestureDetector on path from Column to Expanded

So the problem was that Expanded needs to be a direct child of the Row. Putting the GestureDetector on the Text widget did the trick:

Expanded(
  child: GestureDetector(
    child: Text(
      displayTime ? "Text" : "Other text"
      style: ts),
    onTap: () {},
  ),
),

Hopefully my post and self answer will help someone else.

Thanks!