How to display body under the AppBar of scaffold widget and not below?

后端 未结 7 1686
谎友^
谎友^ 2021-02-03 20:16

I\'m using a transparent AppBar and I would like to display body behind the transparent AppBar and not bellow. How to do that ?

7条回答
  •  -上瘾入骨i
    2021-02-03 20:33

    To place the body under the AppBar and make the AppBar transparent requires a Stack as the body. The Stack must contain the AppBar not the scaffold.

    body: Stack(
            children: [...]
    ),
    

    The first item in the stack is at the bottom and subsequent items are above it. If the AppBar is transparent it will appear to be working, but it is not. Making the AppBar green will show you why.

    return Scaffold(
          body: Stack(
            children: [
              Container(
                color: Colors.blue,
              ),
              AppBar(title: Text('Hello world'),
                backgroundColor: Colors.green,
              )
            ],);
    

    As you can see the AppBar takes up the entire screen and will consume any touch events.

    To fix this use a Position Widget,

    body: Stack(
            children: [
              Container(
                color: Colors.blue,
              ),
              new Positioned(
              top: 0.0,
              left: 0.0,
              right: 0.0,
              child: AppBar(title: Text('Hello world'),
                backgroundColor: Colors.green,
              ),),
            ], )
    

    And you will get this:

    Ok now make the AppBar transparent and remove the shadow:

    body: Stack(
            children: [
              Container( //My container or any other widget
                color: Colors.blue,
              ),
              new Positioned( //Place it at the top, and not use the entire screen
              top: 0.0,
              left: 0.0,
              right: 0.0,
              child: AppBar(title: Text('Hello world'),
                backgroundColor: Colors.transparent, //No more green
                elevation: 0.0, //Shadow gone
              ),),
            ], )
    

    Hope this helps...

提交回复
热议问题