Flutter Spacer 靈活配置你的Row/Column

咱們平時在寫 Row/Column 的時候,通常會配置一會兒widget 的排列方式。git

默認排序方式

默認的排列方式有以下:github

enum MainAxisAlignment {

  /// 將children放置在主軸的起點
  start,

  /// 將children放置在主軸的末尾
  end,

  /// 將children放置在主軸的中心
  center,

  /// 將主軸方向上的空白區域均分,使得children之間的空白區域相等,首尾child都靠近首尾,沒有間隙
  spaceBetween,

  /// 將主軸方向上的空白區域均分,使得children之間的空白區域相等,可是首尾child的空白區域爲1/2
  spaceAround,

  /// 將主軸方向上的空白區域均分,使得children之間的空白區域相等,包括首尾child
  spaceEvenly,
}
複製代碼

看圖瞭解一下。bash

spaceBetween:markdown

spaceAround:less

spaceEvenly:ide

能夠看到確實如咱們剛纔所寫的同樣。flex

不規則排序

那若是這個時候我想實現以下效果,該怎麼作?ui

WX20190531-224832@2x

一個小方塊在最前面,兩個小方塊在後面。this

這個時候就須要Spacer,那什麼是Spacer,按照慣例來看官方文檔:spa

Spacer creates an adjustable, empty spacer that can be used to tune the spacing between widgets in a Flex container, like Row or Column.

Spacer建立一個可調整的空間隔,可用於調整Flex容器(如行或列)中窗口小部件之間的間距。
複製代碼

接下來再看一下該類,肯定一下怎麼使用:

class Spacer extends StatelessWidget {
  /// Creates a flexible space to insert into a [Flexible] widget.
  ///
  /// The [flex] parameter may not be null or less than one.
  const Spacer({Key key, this.flex = 1})
    : assert(flex != null),
      assert(flex > 0),
      super(key: key);

  /// 用於肯定佔用多少空間的彈性係數。
  /// 在放置不靈活的子對象後,根據子對象的彈性係數,將自由空間按比例分割,
  /// 從而肯定[間隔對象]在主軸中能夠佔用的空間量。默認爲1。
  final int flex;

  @override
  Widget build(BuildContext context) {
    return Expanded(
      flex: flex,
      child: const SizedBox.shrink(),
    );
  }
}
複製代碼

能夠看到,它其實就是包裝了一個 Expanded 的 SizedBox 。

知道了原理之後咱們就能夠靈活控制 Row/Column了。

示例以下:

body: Center(
  child: Row(
    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
    children: <Widget>[
      Container(
        color: Colors.blue,
        margin: EdgeInsets.symmetric(horizontal: 5),
        height: 50,
        width: 50,
      ),
      Spacer(flex: 2), // 彈性係數爲2
      Container(
        color: Colors.blue,
        height: 50,
        margin: EdgeInsets.symmetric(horizontal: 5),
        width: 50,
      ),
      Spacer(), // 彈性係數默認爲1
      Container(
        color: Colors.blue,
        margin: EdgeInsets.symmetric(horizontal: 5),
        height: 50,
        width: 50,
      ),
    ],
  ),
)
複製代碼

效果以下:

總結

其實Spacer 就是包裝好的 Expanded,可是這樣也簡化了咱們不少的代碼。

在 Flutter 中還有不少能簡化咱們代碼的地方。

關注我,天天分享 Flutter & Dart 相關知識。

完整代碼已經傳至GitHub:github.com/wanglu1209/…

相關文章
相關標籤/搜索