Flutter 相对布局之Stack

效果

在这里插入图片描述

简介

相对布局,类似于android中的RelativeLayoutFrameLayout
既可以相对父容器确定自己的位置,也可以多个widget重叠显示。
StackPositioned搭配使用。

源码

Stack

  Stack({
    Key key,
    this.alignment = AlignmentDirectional.topStart,
    this.textDirection,
    this.fit = StackFit.loose,
    this.overflow = Overflow.clip,
    List<Widget> children = const <Widget>[],
  }) 
  • alignment :对齐方式,即没有位置定位的widget的对齐方式,当只有横向定位时,比如left有实参,则影响其纵向的对齐方式,再如子widget的top有值,即纵向定位有效,则影响其横向的对齐方式。
  • fit:没有定位的子widget的大小,默认StackFit.loose,使用子widget的大小,StackFit.expand则填充stack
  • overflow :超出stack的显示方式,默认Overflow.clip裁剪,Overflow.visible超出也显示。

Positioned

  const Positioned({
    Key key,
    this.left,
    this.top,
    this.right,
    this.bottom,
    this.width,
    this.height,
    @required Widget child,
  }) 
  • 主要用到lefttoprightbottom四个参数来定位。

示例

如效果图所示,一个简单的登录界面,顶部的logo和底部的登录button是重叠显示在中间Card之上的。
所以我们大概结构就是一个Stack下有3个child,一个未定位的Card,和两个定位的Positioned

        Stack(alignment: Alignment.topCenter, children: <Widget>[
          Container(
            margin: EdgeInsets.only(top: 50),
            padding: EdgeInsets.all(40),
            child: Card(
              ...
            ),
          ),
          Positioned(
            top: 40,
            left: MediaQuery.of(context).size.width / 2 - 35,
            child: Center(
              ...
            ),
          ),
          Positioned(
            bottom: 20,
            left: 130,
            right: 130,
            ...
          ),
        ]),
  • 第一个就是Container,包裹住Card,主要是内填充和外填充。
  • 第二个就是logo,主要是左边位置是屏幕的一半减去自身的一半。
  • 第三个就是底部登录button了。

具体位置显示还要根据自己需求调试。

Github

https://github.com/yechaoa/wanandroid_flutter


发布了246 篇原创文章 · 获赞 441 · 访问量 68万+

猜你喜欢

转载自blog.csdn.net/yechaoa/article/details/99302810