Daniel Oliveira
Daniel Oliveira

Reputation: 8963

How to position a Widget in a Stack, but without matching parent's width/height?

I want to position a widget in the top center of my Stack, but it is getting stretched to the parent's width like the screenshot below:

enter image description here

And this is the code I am using:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      key: key,
      appBar: AppBar(
        title: Text("Just a test app"),
      ),
      body: Stack(
        children: <Widget>[
          Positioned(
            left: 0,
            right: 0,
            child: Card(
              child: Text("A variable sized text"),
            ),
          ),
        ],
      ),
    );
  }

What I am trying to achieve is this (but inside a Stack): enter image description here

Upvotes: 0

Views: 44

Answers (1)

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 277097

Wrap your Card into an Align or Center:

 Stack(
    children: <Widget>[
      Positioned( 
        top: 50,
        left: 0,
        right: 0,
        child: Center(
          child: Card(
            child: Text("A variable sized text"),
          ),
        ),
      ),
      Align(
        alignment: Alignment.topCenter, //that also works
        child: Card(
          child: Text("Another variable sized text"),
        ),
      )
    ],
  ),   

Upvotes: 1

Related Questions