Web 开发者如何理解 Flutter 布局之 —— 4. Row 和 Column

365 阅读1分钟

《Web 开发者如何理解 Flutter 布局》

本系列旨在帮助 Web 前端开发者更好的理解 Flutter 的布局组件,只做对应的语法映射描述和最基本的技术说明。


行/列组件。

  • 通过 Row(列) 设置纵向布局
  • 通过 Column(行) 设置横向布局
  • 通过 MainAxisAlignment(主轴对齐) 设置主轴的对齐方式

1、列组件的使用

Row(
  children: <Widget>[
    Expanded(
      flex: 1,
      child: Text("Row 1")
    ),
    Expanded(
      flex: 1,
      child: Text("Row 2")
    ),
    Expanded(
      flex: 1,
      child: Text("Row 3")
    )
  ]
);

等效于

<div
  style=
  "
    display: flex;
    flex-direction: row;
  "
>
  <div style="flex: 1;">Row 1</div>
  <div style="flex: 1;">Row 2</div>
  <div style="flex: 1;">Row 3</div>
</div>

2、行组件的使用

Column(
  children: <Widget>[
    Expanded(
      flex: 1,
      child: Text("Column 1")
    ),
    Expanded(
      flex: 1,
      child: Text("Column 2")
    ),
    Expanded(
      flex: 1,
      child: Text("Column 3")
    )
  ]
);

等效于

<div
  style=
  "
    display: flex;
    flex-direction: column;
    height: 100%;
  "
>
  <div style="flex: 1;">Column 1</div>
  <div style="flex: 1;">Column 2</div>
  <div style="flex: 1;">Column 3</div>
</div>

3、设置主轴对齐方式

Row(
  mainAxisAlignment: MainAxisAlignment.spaceBetween,
  children: <Widget>[
    Container(
      child: Text("Row 1"),
      width: 80.0,
      color: Colors.red
    ),
    Container(
      child: Text("Row 1"),
      width: 80.0,
      color: Colors.yellow
    ),
    Container(
      child: Text("Row 1"),
      width: 80.0,
      color: Colors.green
    )
  ]
);

等效于

<div
  style=
  "
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  "
>
  <div
    style=
    "
      flex: 1;
      max-width: 80px;
      background-color: red;
    "
  >Column 1</div>
  <div
    style=
    "
      flex: 1;
      max-width: 80px;
      background-color: yellow;
    "
  >Column 1</div>
  <div
    style=
    "
      flex: 1;
      max-width: 80px;
      background-color: green;
    "
  >Column 1</div>
</div>

其中,Flutter 与 web 等效的表格映射如下:

主轴对齐模式 web 实现 flutter 实现
起始点对齐 flex-start MainAxisAlignment.start
中点对齐 center MainAxisAlignment.center
终止点对齐 flex-end MainAxisAlignment.end
环绕对齐 space-around MainAxisAlignment.spaceAround
分散对齐 space-between MainAxisAlignment.spaceBetween
等距对齐 space-evenly MainAxisAlignment.spaceEvenly