Flutter: How to make a Card overlap the AppBar?

hendra picture hendra · Mar 24, 2018 · Viewed 11.8k times · Source

How can I make a Card in Flutter that overlaps the AppBar? Negative margins are not possible as far as I know.

See the image for clarity.

<code>Card</code> floating above the <code>AppBar</code>

Answer

German Saprykin picture German Saprykin · Mar 25, 2018

For one card it could be easily done with Stack widget

E.g.

import 'package:flutter/material.dart';

class Home extends StatefulWidget {
  Home({Key key}) : super(key: key);

  @override
  HomeState createState() {
    return new HomeState();
  }
}

class HomeState extends State<Home> {
  bool _hasCard;

  @override
  void initState() {
    super.initState();
    _hasCard = false;
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> children = new List();

    children.add(_buildBackground());
    if (_hasCard) children.add(_buildCard());

    return MaterialApp(
      home: Stack(
        children: children,
      ),
    );
  }

  void _showCard() {
    setState(() => _hasCard = true);
  }

  void _hideCard() {
    setState(() => _hasCard = false);
  }

  Widget _buildCard() => new Container(
        child: new Center(
          child: new Container(
            height: 700.0,
            width: 200.0,
            color: Colors.lightBlue,
            child: new Center(
              child: new Text("Card"),
            ),
          ),
        ),
      );

  Widget _buildBackground() => new Scaffold(
        appBar: new AppBar(
          title: new Text("AppBar"),
        ),
        body: new Container(
          child: _hasCard
              ? new FlatButton(
                  onPressed: _hideCard, child: new Text("Hide card"))
              : new FlatButton(
                  onPressed: _showCard, child: new Text("Show card")),
        ),
      );
}

void main() {
  runApp(
    new Home(),
  );
}

If there are many cards, you can wrap them into ListView.