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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章