Flutter布局Widget--彈性布局、線性布局、流式布局和層疊布局

前言

本文我們要介紹 Flutter 中布局 Widget,包括彈性布局、線性布局
流式布局和層疊布局。

一、彈性布局--Flex

Flex 類似 Android 中的 FlexboxLayout,和 Expanded 配合使用可以實現(xiàn)子Widget 按照一定比例來分配父容器空間。

  • 使用:
Flex(
    direction: Axis.horizontal,
    children: <Widget>[
      ...
    ],
)

其中direction:主軸的方向,是必選參數(shù),它的類型是 Axis,有以下兩種值:
(1)Axis.horizontal:主軸方向為水平方向,那么子Widget 就會沿水平方向排列,交叉方向是垂直方向。
(2)Axis.vertical:主軸方向為垂直方向,那么子Widget 就會沿垂直方向排列,交叉方向是水平方向。

  • Flex 的構(gòu)造函數(shù)及參數(shù)說明
class Flex extends MultiChildRenderObjectWidget {
  Flex({
    Key key,
    @required this.direction,//必選;類型 Axis;主軸的方向
    this.mainAxisAlignment = MainAxisAlignment.start,//可選;類型 MainAxisAlignment;表示子Widget在主軸的對齊方式
    this.mainAxisSize = MainAxisSize.max,//可選;類型 MainAxisSize;表示主軸應(yīng)該占用多大的空間,分為mix 和 max
    this.crossAxisAlignment = CrossAxisAlignment.center,//可選;類型 CrossAxisAlignment;表示子Widget在交叉軸的對齊方式
    this.textDirection,//可選;類型 TextDirection;表示子Widget在主軸方向上的布局順序,分為rtl:從右到左 和 ltr:從左到右
    this.verticalDirection = VerticalDirection.down,//可選;類型 VerticalDirection;表示子Widget在交叉軸方向上的布局順序
    this.textBaseline,//可選;類型 TextBaseline;排列子Widget 時使用哪個基線
    List<Widget> children = const <Widget>[],//可選;類型 List< Widget>;Flex布局 里排列的內(nèi)容
  }) : assert(direction != null),
       assert(mainAxisAlignment != null),
       assert(mainAxisSize != null),
       assert(crossAxisAlignment != null),
       assert(verticalDirection != null),
       assert(crossAxisAlignment != CrossAxisAlignment.baseline || textBaseline != null),
       super(key: key, children: children);
    ...
}
  • Flexible 與 Expanded
    為了避免子Widget 在 Row、Column、Flex中超屆,就可以使用 Flexible 和 Expanded,當(dāng)子Widget 要超過主軸的大小時,會自動換行。其中 Expanded 是 Flexible 的子類。
Flexible(
    child: Text('內(nèi)容'),
  )
//或
Expanded(
    child: Text('內(nèi)容'),
  )

(1)Flexible 的構(gòu)造函數(shù)及參數(shù)說明:

class Flexible extends ParentDataWidget<Flex> {
  const Flexible({
    Key key,
    this.flex = 1, //可選;類型 int;此 Widget的彈性因子
    this.fit = FlexFit.loose,//可選;類型 FlexFit;如何分配彈性Widget在可用空間里的大小
    @required Widget child,//必選;類型 Widget;要顯示的Widget
  }) : super(key: key, child: child);
  ...
}

(2)Expanded 的構(gòu)造函數(shù)及參數(shù)說明:

class Expanded extends Flexible {
  /// Creates a widget that expands a child of a [Row], [Column], or [Flex]
  /// expand to fill the available space in the main axis.
  const Expanded({
    Key key,
    int flex = 1,
    @required Widget child,
  }) : super(key: key, flex: flex, fit: FlexFit.tight, child: child);
}

(3)Flexible 與 Expanded 的區(qū)別:
fit 參數(shù)不同,Expanded 用的是默認(rèn)的,當(dāng)還有剩余空間的時候,會占滿剩余的全部空間。而 Flexible 用的是 FlexFit.loose,只占用自身大小的空間。
(4)flex 彈性系數(shù):
當(dāng) flex 為0或null,則 child 是沒有彈性的,稱為非彈性子Widget,非彈性子Widget的大小就是其本身的大小,不會被擴(kuò)展去占用多余的空間 。
當(dāng) flex 大于0時,child 是有彈性的,稱為彈性子Widget,首先會計算出第一步所有 flex 為0或null的子Widget 的大小,然后會按照彈性子Widget的flex占所有彈性子Widget的flex總和的比例分割主軸的空閑空間。

二、線性布局

Flutter 的線性布局和 Android 中的一樣分為水平方向的線性布局Row和垂直方向的線性布局Column。

1. Row

  • 使用:
Row(
  children: <Widget>[
    Text("Hello Flutter"),
    Image.asset(
      "images/flutter.png",
      width: 200,
    )
  ],
)
  • Row 的構(gòu)造函數(shù)及參數(shù)說明:
class Row extends Flex {
  Row({
    Key key,
    MainAxisAlignment mainAxisAlignment = MainAxisAlignment.start,//可選;類型 MainAxisAlignment;表示子Widget 在主軸的對齊方式
    MainAxisSize mainAxisSize = MainAxisSize.max,//可選;類型 MainAxisSize;表示主軸應(yīng)該占用多大的空間
    CrossAxisAlignment crossAxisAlignment = CrossAxisAlignment.center,//可選;類型 CrossAxisAlignment;表示子Widget在交叉軸的對齊方式
    TextDirection textDirection,//可選;類型TextDirection;表示子Widget在主軸方向上的布局參數(shù)
    VerticalDirection verticalDirection = VerticalDirection.down,//可選;類型VerticalDirection;表示子Widget在交叉軸方向上的布局順序
    TextBaseline textBaseline,//可選;類型TextBaseline;排列子Widget時使用哪個基線
    List<Widget> children = const <Widget>[],//可選;類型List< Widget>;Flex布局里排列的內(nèi)容
  }) : super(
    children: children,
    key: key,
    direction: Axis.horizontal,
    mainAxisAlignment: mainAxisAlignment,
    mainAxisSize: mainAxisSize,
    crossAxisAlignment: crossAxisAlignment,
    textDirection: textDirection,
    verticalDirection: verticalDirection,
    textBaseline: textBaseline,
  );
}

2. Column

  • 使用:
Column(
  children: <Widget>[
    Text("Hello Flutter"),
    Image.asset(
      "images/flutter.png",
      width: 200,
    )
  ],
)
  • Column 的構(gòu)造函數(shù)及參數(shù)說明:
    和 Row 的參數(shù)一樣

注意:如果 Row 嵌套 Row,或者 Column 嵌套 Column,那么只有最外面的 Row 或 Column 會占用盡可能大的空間,里面 Row 或 Column 所占用的空間為實際的大小。

三、流式布局--Wrap

頁面元素的寬度可以按照屏幕分辨率進(jìn)行適配調(diào)整,把超出屏幕顯示范圍的控件自動換行。

  • 使用:
Wrap(
  direction: Axis.horizontal,
  children: <Widget>[
    ...
  ]
)
  • 代碼示例:
import 'package:flutter/material.dart';

class WrapWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'WrapWidget',
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('WrapWidget'),
        ),
        body: Wrap(
          direction: Axis.horizontal,
          spacing: 10.0,
          runSpacing: 5.0,
          children: <Widget>[
            new Chip(
                avatar: new CircleAvatar(
                  backgroundColor: Colors.blue,
                  child: new Text('1'),
                ),
                label: new Text('AAAAAAAAAA')),
            new Chip(
                avatar: new CircleAvatar(
                  backgroundColor: Colors.blue,
                  child: new Text('1'),
                ),
                label: new Text('BBBBB')),
            new Chip(
                avatar: new CircleAvatar(
                  backgroundColor: Colors.blue,
                  child: new Text('1'),
                ),
                label: new Text('CCCCCCCCCCC')),
            new Chip(
                avatar: new CircleAvatar(
                  backgroundColor: Colors.blue,
                  child: new Text('2'),
                ),
                label: new Text('DDDDDDDD')),
            new Chip(
                avatar: new CircleAvatar(
                  backgroundColor: Colors.blue,
                  child: new Text('2'),
                ),
                label: new Text('EEEEEE')),
          ],
        ),
      ),
    );
  }
}
  • 運行結(jié)果:
  • Wrap 的構(gòu)造函數(shù)及參數(shù)說明:

class Wrap extends MultiChildRenderObjectWidget {
  Wrap({
    Key key,
    this.direction = Axis.horizontal,//可選;類型 Axis;主軸的方向,默認(rèn)是 Axis.horizontal
    this.alignment = WrapAlignment.start,//可選;類型 WrapAlignment;子Widget在主軸上的對齊方式,默認(rèn)值為WrapAlignment.start,和MainAxisAlignment的一樣
    this.spacing = 0.0,//可選;類型 double;主軸的方向間距
    this.runAlignment = WrapAlignment.start,//可選;類型 WrapAlignment;Wrap 會自動換成或換列,runAlignment 就是每行或每列的對齊方式,如果主軸為水平方向,就是每行,如果主軸為豎直方向,就是每列,默認(rèn)值為WrapAlignment.start,WrapAlignment 的值和 MainAxisAlignment 的一樣
    this.runSpacing = 0.0,//可選;類型 double;每行或每列之間的間距,默認(rèn)是0.0
    this.crossAxisAlignment = WrapCrossAlignment.start,//可選;類型 WrapCrossAlignment;子Widget 在交叉軸上的對齊方式,WrapCrossAligment.start,WrapCrossAligment的值和MainAxisAligment的一樣
    this.textDirection,//可選;類型 TextDirection;表示子Widget在主軸方向上的布局順序
    this.verticalDirection = VerticalDirection.down,//可選;類型 VerticalDirection;表示子Widget在交叉軸方向上的布局順序
    List<Widget> children = const <Widget>[],//可選;類型 List<Widget>;Wrap布局里排序的內(nèi)容
  }) : super(key: key, children: children);
  ...
}

四、層疊布局--Stack

Flutter 中的層疊布局類似 Android 中的 FrameLayout,其子Widget 會按照添加順序確定顯示層級,后面添加的會覆蓋在前面添加的 Widget 上面。

  • 使用:
Stack(
  children: <Widget>[
    Image.asset(
      "images/flutter.png",
       width: 200,
       fit: BoxFit.cover,
    ),
    Text('Hello Flutter',style: TextStyle(fontSize: 50.0),),
  ],
)
  • Stack 的構(gòu)造函數(shù)及參數(shù)說明:
class Stack extends MultiChildRenderObjectWidget {
  Stack({
    Key key,//可選;類型 Key;Widget的標(biāo)識
    this.alignment = AlignmentDirectional.topStart,//可選;類型AlignmentDirectional
    this.fit = StackFit.loose,//可選;類型 StackFit;此參數(shù)用于決定 non-positioned 子Widget 如何去適應(yīng)Stack的大小
    this.overflow = Overflow.clip,//可選;類型 Overflow;決定如何顯示超出 Stack顯示空間的子Widget
    List<Widget> children = const <Widget>[],//可選;類型 List<Widget>;Stack布局里排序的內(nèi)容
  }) : super(key: key, children: children);
  ...
}

(1)alignment 參數(shù):
決定如何對齊 non-positioned 子Widget 和部分 position 子Widget,默認(rèn)值為Alignment.topStart,部分 positioned 子Widget,在某一個軸上沒有定義的,這個軸就使用 alignment 的值,比如left、right為橫軸,left 和right 都沒有定義,就是橫軸沒有定義,只要這兩個一個有值,這個軸就算有值;top、bottom為縱軸,同理。

AlignmentDirectional 的值:
AlignmentDirectional.topStart:上邊 start 對齊
AlignmentDirectional.topCenter:上邊 居中 對齊
AlignmentDirectional.topEnd:上邊 end 對齊
AlignmentDirectional.centerStart:中間 start 對齊
AlignmentDirectional.center:中間對齊
AlignmentDirectional.centerEnd:中間 end 對齊
AlignmentDirectional.bottomStart:下邊 start 對齊
AlignmentDirectional.bottomCenter:下邊 居中 對齊
AlignmentDirectional.bottomEnd:下邊 end 對齊

(2)fit 參數(shù):
用于決定 non-positioned 子Widget 如何去適應(yīng)Stack的大小。

StackFit 的值:
StackFit.loose:使用子Widget 自身的大小
StackFit.expand:子Widget 擴(kuò)伸到 Stack 的大小
StackFit.passthrough:Stack 的父Widget 的約束無修改的傳遞給 Stack 的子Widget

(3)overflow 參數(shù):
決定如何顯示超出 Stack顯示空間的子Widget。

overflow 的值:
Overflow.visible:超出部分仍能看見
Overflow.clip:超出部分會被剪裁

  • Stack 的子Widget
    為了確定子Widget 到父容器四個角的位置,Stack將子Widget 分為兩類:positioned 子Widget 和 non-positioned 子Widget。
    (1)Positioned
    positioned 子Widget 是指被 Positioned 嵌套起來的 Widget,Positioned 可以控制子Widget 到父容器四個邊的距離。

使用:

Stack(
          fit: StackFit.expand,
          children: <Widget>[
            Positioned(
              left: 50,
              top: 100,
              child: Image.asset(
                "images/flutter.png",
                width: 200,
                fit: BoxFit.cover,
              ),
            ),
            Text('Hello Flutter'),
          ],
        ),

Positioned 的構(gòu)造函數(shù)及參數(shù)說明:

class Positioned extends ParentDataWidget<Stack> {
  const Positioned({
    Key key,//可選;類型 Key;Widget的標(biāo)識
    this.left,//可選;類型 double;離Stack左邊的距離
    this.top,//可選;類型 double;離Stack上邊的距離
    this.right,//可選;類型 double;離Stack右邊的距離
    this.bottom,//可選;類型 double;離Stack底邊的距離
    this.width,//可選;類型 double;指定Widget的寬度
    this.height,//可選;類型 double;指定Widget的高度
    @required Widget child,
  }) : assert(left == null || right == null || width == null),
       assert(top == null || bottom == null || height == null),
       super(key: key, child: child);
    ...
}

注意:此處的width、height 是用于配合 left、top、right、bottom 來定位 Widget 的。并且在水平方向上,只能指定 left、right、width 三個屬性中的兩個,如果三個都指定就會報錯;垂直方向同理。

(2)non-positioned子Widget
non-positioned 子Widget 就是不用 Positioned 嵌套起來的 Widget,non-positioned 子Widget 使用 Stack 設(shè)置的 alignment 來確定自己在父容器里的位置。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容