56

Is there a way to size a stack child automatically to its largest sibling? I.e. if I have a Stack with a ListTile and a Container on top, how do I make sure the Container covers the entire ListTile?

Example:

new Stack(children: <Widget>[
      new ListTile(
          leading: new AssetImage('foo.jpg'),
          title: new Text('Bar'),
          subtitle: new Text('yipeee'),
          isThreeLine: true,
      ),
      new Container(color: Colors.grey, child: new Text('foo'))
 ],
)

I tried to make it work with Row, Column and Expanded but am running into problems with unbounded constraints.

Is there a way to size the Container (or any other widget such as a GestureDetector) to its largest sibling in the stack?

TommyF
  • 6,660
  • 8
  • 37
  • 61

1 Answers1

147

I had the same issue and finally managed to solve it using this answer:

Inside your Stack, you should wrap your background widget in a Positioned.fill.

return new Stack(
  children: <Widget>[
    new Positioned.fill(
      child: background,
    ),
    foreground,
  ],
);

-- Mary, https://stackoverflow.com/a/45745479

Applying that to your question results in the following:

Stack(
  children: <Widget>[
    ListTile(
      leading: AssetImage('foo.jpg'),
      title: Text('Bar'),
      subtitle: Text('yipeee'),
      isThreeLine: true,
    ),
    Positioned.fill(
      child: Container(color: Colors.grey, child: Text('foo')),
    ),
  ],
),
nesbocaj
  • 1,663
  • 1
  • 8
  • 8
  • 8
    Just to clarify - the widget that should be wrapped in a `Positioned.fill` is the one that should adjust its size to its sibling. Wether that's the background or foreground widget depends on your use case (the quoted answer wraps the background widget, while this answer wraps the foreground widget). – Magnus Sep 08 '20 at 14:10
  • 1
    Does the trick for me. Thanks! – Adrian Moisa Sep 20 '21 at 21:17