Column和Row
最常见的布局模式之一是垂直或水平 widgets。可以使用 Row widget 水平排列 widgets,使用 Column widget 垂直排列 widgets。
- Row 和 Column 是两种最常用的布局模式。
- Row and Column each take a list of child widgets.
Row
和Column
每个都有一个子 widgets 列表。 - 一个子 widget 本身可以是 Row、Column 或其他复杂 widget。
- 可以指定 Row 或 Column如何在垂直和水平方向上对齐其子项。
- 可以拉伸或限制特定的子 widgets。
- 可以指定子 widgets 如何占用 Row 或 Column 的可用空间。
对齐策略
Column和Row的对齐策略其实是一致的,只不过Column的基准是纵向,Row的对齐基准是横向。
基准成为Main,交叉的成为Cross。因此有了下图。
Column和Row的属性:
- mainAxisSize:main axis上所占据的空间。
MainAxisSize.max表示Column或Row占据了所有空间。不管内部的children占据多大空间,Column和Row会撑满他们父组件在main axis上的所有空间。
MainAxisSize.min:表示Column和Row只会根据自己children的大小来占据空间。 - mainAxisAlignment:Column和Row怎么分配children未占据的空间。
如果mainAxisSize 被设为 MainAxisSize.max,这个属性才有意义。如果MainAxisSize.min, 则Column或Row没有多余的空间,就不需要考虑mainAxisAlignment。
属性名 | 属性描述 |
---|---|
MainAxisAlignment.start | 将其 children 从主轴起点处开始对齐。 (Row 的起点在左边,Column 的起点在顶部 ) |
MainAxisAlignment.end | 将其 children 从主轴终点处开始对齐。 (Row 的终点在右边,Column 的终点在底部 ) |
MainAxisAlignment.center | 将其 children 置于主轴中心。 |
MainAxisAlignment.spaceBetween | 在 children 之间平均分配额外空间。 |
MainAxisAlignment.spaceEvenly | 在 children 之间,以及第一个 children 之前和最后一个 children 之后,平均分配额外空间。 |
MainAxisAlignment.spaceAround | 与 MainAxisAlignment.spaceEvenly 相似,但在第一个 child 之前以及最后一个孩子之后减少了一半的空间,让其 children 之间宽度缩减一半。 |
- crossAxisAlignment 。决定了 Row 和 Column 能够如何在其横轴上定位 children。
属性 | 描述 |
---|---|
CrossAxisAlignment.start | 将其 children 横轴顶部对齐。 (顶部是 Row,左侧是 Column ) |
CrossAxisAlignment.start | Positions children near the start of the cross axis. (Top for Row, Left for Column) |
CrossAxisAlignment.end | 将其 children 横轴底部对齐。 (底部是 Row,右侧是 Column ) |
CrossAxisAlignment.center | 将其 children 横轴中心对齐。 (中间是 Row,中心是 Column ) |
CrossAxisAlignment.stretch | 沿横轴延伸 children。 (在 Row 中是从顶至底,Column 则是从左至右 ) |
CrossAxisAlignment.baseline | 根据 children 的基线对子节点。 (仅限Text类,并要求 textBaseline 属性设置为 TextBaseline.alphabetic。在 Text class 小节中查看样例。 |
例子
Row占用父组件所有的空间。Row的children之间平均分配多余的空间。
Row占用父组件所有空间,Row的children之间平均分配多余空间。但和之前的区别是,第一个child之前和最后一个child之后也占据空间。
Row占用最小空间。此时mainAxisAlignment的设置没有意义。
cross对齐策略。
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
width: 200,
height: 100,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
BlueBox(),
BiggerBlueBox(),
BlueBox(),
],
));
}
}
class BlueBox extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
width: 50,
height: 50,
decoration: BoxDecoration(
color: Colors.blue,
border: Border.all(),
),
);
}
}
class BiggerBlueBox extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
width: 50,
height: 100,
decoration: BoxDecoration(
color: Colors.blue,
border: Border.all(),
),
);
}
}