Flutter - Overlay card widget on a container

Praveen Kumar picture Praveen Kumar · Mar 21, 2018 · Viewed 25k times · Source

In flutter, is it possible to place a part of a card on another container? In CSS, we would set margin-top to a negative value or use translate property. In flutter as we cannot set negative values to margin-top, is there an alternative to that?

enter image description here

Answer

Hemanth Raj picture Hemanth Raj · Mar 21, 2018

Yes, you can acheive it with a Stack widget. You can stack a card over the background and provide a top or bottom padding.

A simple example would look like:

class StackDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Stack(
      children: <Widget>[
        // The containers in the background
        new Column(
          children: <Widget>[
            new Container(
              height: MediaQuery.of(context).size.height * .65,
              color: Colors.blue,
            ),
            new Container(
              height: MediaQuery.of(context).size.height * .35,
              color: Colors.white,
            )
          ],
        ),
        // The card widget with top padding, 
        // incase if you wanted bottom padding to work, 
        // set the `alignment` of container to Alignment.bottomCenter
        new Container(
          alignment: Alignment.topCenter,
          padding: new EdgeInsets.only(
              top: MediaQuery.of(context).size.height * .58,
              right: 20.0,
              left: 20.0),
          child: new Container(
            height: 200.0,
            width: MediaQuery.of(context).size.width,
            child: new Card(
              color: Colors.white,
              elevation: 4.0,
            ),
          ),
        )
      ],
    );
  }
}

The output of the above code would look something like:

Output Image

Hope this helps!